<?php

/**
 * ECSHOP 会员中心
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: user.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
$smarty->assign('footer', get_footer());

/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');

$user_id = $_SESSION['user_id'];

if(!empty($user_id)){
    $sql = 'SELECT agent_rank FROM '.$ecs->table('users')."WHERE user_id = ".$user_id;
    $agent_rank = $db->getOne($sql);
}
$smarty->assign('agent_rank', $agent_rank);

$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';
/*4.1活动*/
$times = time();
if ($times>1427860800&&$times<1428595200) {
$smarty->assign('num_4_1', 1);
}
$affiliate = unserialize($GLOBALS['_CFG']['affiliate']);
$smarty->assign('affiliate', $affiliate);
$back_act='';
// 不需要登录的操作或自己验证是否登录（如ajax处理）的act
$not_login_arr =
array('login','act_login','register','act_register','act_edit_password','get_password','send_pwd_email','password', 'signin', 'add_tag', 'collect', 'return_to_cart', 'logout', 'email_list', 'validate_email', 'send_hash_mail', 'order_query', 'is_registered', 'check_email','clear_history','qpassword_name', 'get_passwd_question', 'check_answer','ajax_register');

/* 显示页面的action列表 */
$ui_arr = array('register', 'login', 'profile', 'order_list', 'order_detail', 'address_list','address_up','address_add', 'freeplan','freeplan_info', 'collection_list', 'my_recommend', 'my_recommend_action',
'message_list', 'tag_list', 'get_password', 'reset_password', 'booking_list', 'add_booking', 'account_raply',
'account_deposit', 'account_log', 'account_detail', 'act_account', 'pay', 'default', 'bonus', 'group_buy', 'group_buy_detail', 'affiliate', 'comment_list','validate_email','track_packages', 'transform_points','qpassword_name', 'get_passwd_question', 'check_answer','sale_service','sale_service_form','done','error', 'sale_list',"sale_detail",'payCode','coupon');
/* 未登录处理 */
if (empty($_SESSION['user_id']))
{
    if (!in_array($action, $not_login_arr))
    {
        if (in_array($action, $ui_arr))
        {
            /* 如果需要登录,并是显示页面的操作，记录当前操作，用于登录后跳转到相应操作
            if ($action == 'login')
            {
                if (isset($_REQUEST['back_act']))
                {
                    $back_act = trim($_REQUEST['back_act']);
                }
            }
            else
            {}*/
            if (!empty($_SERVER['QUERY_STRING']))
            {
                $back_act = 'user.php?' . strip_tags($_SERVER['QUERY_STRING']);
            }
            $action = 'login';
        }
        else
        {
            //未登录提交数据。非正常途径提交数据！
            die($_LANG['require_login']);
        }
    }
}
 $smarty->assign('top_title',  $_LANG[$action]);//顶部标题
 $smarty->assign('user',  "1");//顶部标题
/* 如果是显示页面，对页面进行相应赋值 */
if (in_array($action, $ui_arr))
{
    assign_template();//读取通用配置
    $position = assign_ur_here(0, $_LANG['user_center']);
    $smarty->assign('page_title', $position['title']); // 页面标题
    $smarty->assign('ur_here',    $position['ur_here']);
    $sql = "SELECT value FROM " . $ecs->table('shop_config') . " WHERE id = 419";
    $row = $db->getRow($sql);
    $car_off = $row['value'];
    $smarty->assign('car_off',       $car_off);
    /* 是否显示积分兑换 */
    if (!empty($_CFG['points_rule']) && unserialize($_CFG['points_rule']))
    {
        $smarty->assign('show_transform_points',     1);
    }
    $smarty->assign('helps',      get_shop_help());        // 网店帮助
    $smarty->assign('action',     $action);
    $smarty->assign('lang',       $_LANG);
    include_once(ROOT_PATH .'mobile/includes/lib_clips.php');
}

//用户中心欢迎页
if ($action == 'default')
{
    include_once(ROOT_PATH .'mobile/includes/lib_clips.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    $smarty->assign('back_url',  "index.php");
    $smarty->display('user_clips.dwt');
}

/* 显示会员注册界面 */
if ($action == 'register')
{
    if ((!isset($back_act)||empty($back_act)) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }

    /* 取出注册扩展字段 */
    $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id';
    $extend_info_list = $db->getAll($sql);
    $smarty->assign('extend_info_list', $extend_info_list);

    /* 验证码相关设置 */
    if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0)
    {
        $smarty->assign('enabled_captcha', 1);
        $smarty->assign('rand',            mt_rand());
    }

    /* 密码提示问题 */
    $smarty->assign('passwd_questions', $_LANG['passwd_questions']);

    /* 增加是否关闭注册 */
    $smarty->assign('shop_reg_closed', $_CFG['shop_reg_closed']);
    $smarty->assign('back_act', $back_act);
    $smarty->display('user_passport.dwt');
}

/* 注册会员的处理 */
elseif ($action == 'act_register')
{
    /* 增加是否关闭注册 */
    if ($_CFG['shop_reg_closed'])
    {
        $smarty->assign('action',     'register');
        $smarty->assign('shop_reg_closed', $_CFG['shop_reg_closed']);
        $smarty->display('user_passport.dwt');
    }
    else
    {
        include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');
        include_once('includes/cls_json.php');
        $json = new JSON;
        $username = isset($_POST['username']) ? trim($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        $email    = isset($_POST['email']) ? trim($_POST['email']) : '';
        $back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';
        $mobile_phone = isset($_POST['mobile_phone']) ? intval($_POST['mobile_phone']) : '';
        /* 验证码检查 */

        if ((intval($_CFG['captcha']) & CAPTCHA_REGISTER) && gd_version() > 0)
        {
            if (empty($_POST['captcha']))
            {
                echo $json->encode("验证码不能为空");
                exit;
            }
            /* 检查验证码 */
            include_once('includes/cls_captcha.php');
            $validator = new captcha();
            if (!$validator->check_word($_POST['captcha']))
            {
                echo $json->encode("验证码错误");
                exit;
            }
        }
        /*用户名字检测*/
       if ($user->check_user($username) || admin_registered($username))
        {
            echo $json->encode("用户名已经存在");
            exit;
        }
        /*邮箱集检测*/
        if ($user->check_email($email))
        {
            echo $json->encode("邮箱已存在");
            exit;
        }

         if (register($username, $password, $email, $mobile_phone) !== false)
        {

            /* 判断是否需要自动发送注册邮件 */
            if ($GLOBALS['_CFG']['member_email_validate'] && $GLOBALS['_CFG']['send_verify_email'])
            {
                send_regiter_hash($_SESSION['user_id']);
            }
            $ucdata = empty($user->ucdata)? "" : $user->ucdata;

            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'MOBILE'."\t".
                get_user_browser()."\t".
                "注册");
            writelog('cplogs', $errorlog);

            echo $json->encode("注册成功");
            exit;
        }
        else
        {

            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'MOBILE'."\t".
                get_user_browser()."\t".
                "注册失败");
            writelog('cplogs', $errorlog);

            echo $json->encode("注册失败");
            exit;
        }
    }
}

// 处理AJAX注册

/* 验证用户注册邮件 */
elseif ($action == 'validate_email')
{
    $hash = empty($_GET['hash']) ? '' : trim($_GET['hash']);
    if ($hash)
    {
        include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');
        $id = register_hash('decode', $hash);
        if ($id > 0)
        {
            $sql = "UPDATE " . $ecs->table('users') . " SET is_validated = 1 WHERE user_id='$id'";
            $db->query($sql);
            $sql = 'SELECT user_name, email FROM ' . $ecs->table('users') . " WHERE user_id = '$id'";
            $row = $db->getRow($sql);
            show_message(sprintf($_LANG['validate_ok'], $row['user_name'], $row['email']),$_LANG['profile_lnk'], 'user.php');
        }
    }
    show_message($_LANG['validate_fail']);
}

/* 验证用户注册用户名是否可以注册 */
elseif ($action == 'is_registered')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');
    $username = trim($_REQUEST['username']);
    $username = json_str_iconv($username);

    if ($user->check_user($username) || admin_registered($username))
    {
        echo 'false';
    }
    else
    {
        echo 'true';
    }
}

/* 验证用户邮箱地址是否被注册 */
elseif($action == 'check_email')
{
    $email = trim($_REQUEST['email']);
    if ($user->check_email($email))
    {
        echo 'false';
    }
    else
    {
        echo 'ok';
    }
}
/* 用户登录界面 */
elseif ($action == 'login')
{
    if (empty($back_act))
    {
        if (empty($back_act) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
        {
            $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
        }
        else
        {
            $back_act = 'user.php';
        }

    }
    /* 检查是否已有登录cookie */
    if (!empty($_COOKIE['ECS']['user_id']) && !empty($_COOKIE['ECS']['username'])) {
        $_SESSION['user_id'] = $_COOKIE['ECS']['user_id'];
        $_SESSION['user_name'] = $_COOKIE['ECS']['username'];
        header("location: $back_act");
        exit;
    }
    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 2);
        $GLOBALS['smarty']->assign('rand', mt_rand());
    }
    $smarty->assign('back_act', $back_act);
    $smarty->display('user_login.dwt');
}

/* 处理会员的登录 */
elseif ($action == 'act_login')
{
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? trim($_POST['password']) : '';
    $back_act = isset($_POST['back_act']) ? trim($_POST['back_act']) : '';

    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        if (empty($_POST['captcha']))
        {
            show_message($_LANG['invalid_captcha'], $_LANG['relogin_lnk'], 'user.php', 'error');
        }

        /* 检查验证码 */
        include_once('includes/cls_captcha.php');
        $validator = new captcha();
        $validator->session_word = 'captcha_login';
        if (!$validator->check_word($_POST['captcha']))
        {
            show_message($_LANG['invalid_captcha'], $_LANG['relogin_lnk'], 'user.php', 'error');
        }
    }

    if ($user->login($username, $password,isset($_POST['remember'])))
    {
        update_user_info();
        recalculate_price();
        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'MOBILE'."\t".
            get_user_browser()."\t".
            "登录");
        writelog('cplogs', $errorlog);
        $ucdata = isset($user->ucdata)? $user->ucdata : '';
        //show_message($_LANG['login_success'] . $ucdata , array($_LANG['back_up_page'], $_LANG['profile_lnk']), array($back_act,'user.php'), 'info');
        ecs_header("Location: user.php\n");
        exit;

    }
    else
    {
        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'MOBILE'."\t".
            get_user_browser()."\t".
            "登录失败");
        writelog('cplogs', $errorlog);
        $_SESSION['login_fail'] ++ ;
        show_message($_LANG['login_failure'], $_LANG['relogin_lnk'], 'user.php', 'error');
    }
}

/* 处理 ajax 的登录请求 */
elseif ($action == 'signin')
{
    include_once('includes/cls_json.php');
    $json = new JSON;
    $url = !empty($_POST['return_url']) ? json_str_iconv(trim($_POST['return_url'])) : 'index.php';
    $username = !empty($_POST['username']) ? json_str_iconv(trim($_POST['username'])) : '';
    $password = !empty($_POST['password']) ? trim($_POST['password']) : '';
    $captcha1 = !empty($_POST['captcha']) ? json_str_iconv(trim($_POST['captcha'])) : '';
    $result   = array('error' => 0, 'content' => '');
    $captcha = intval($_CFG['captcha']);
    // 是否启用验证码
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        if(empty($captcha1)){
            $result['error']=1;
            $result['content']="请输出验证码";
            die($json->encode($result));
        }
        else{
        /* 检查验证码 */
        include_once('includes/cls_captcha.php');
        $validator = new captcha();
        $validator->session_word = 'captcha_login';
        if (!$validator->check_word($_POST['captcha']))
        {
            $result['error']=1;
            $result['content']="验证码错误";
            die($json->encode($result));
        }

        }
    }
    // 判断是否登录成功
    if ($user->login($username, $password,isset($_POST['remember']))){
        update_user_info();  //更新用户信息
            /*查询是否有默认收货地址有则 更改默认配送地区*/
        $sql="SELECT address_id FROM " .$GLOBALS['ecs']->table('users'). " WHERE user_id='".$_SESSION['user_id']."'";
        $address_id=$GLOBALS['db']->getOne($sql);
        if(!empty($address_id)){
            $sql="SELECT * FROM ".$GLOBALS['ecs']->table('user_address')." WHERE address_id='$address_id'";
            $address= $GLOBALS['db']->getRow($sql);
            $_SESSION['address_id']=$address_id;
            set_consignee($address['district']);
        }
        $smarty->assign('user_info', get_user_info());
        $ucdata = empty($user->ucdata)? "" : $user->ucdata;
        $result['url']    =$url;
        $result['ucdata'] = $ucdata;
        $result['content'] = $smarty->fetch('library/member_info.lbi');
        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'MOBILE'."\t".
            get_user_browser()."\t".
            "登录");
        writelog('cplogs', $errorlog);
    }
    else{
        $result['error']   = 1;
        $result['content'] = "帐号或密码错误";

        require_once(ROOT_PATH.'/plugins/ip/ip.php');
        $ip = new ip();
        $addr = $ip->ip2addr(real_ip());
        $errorlog = (
            time()."\t".
            $username."\t".
            '0'."\t".
            real_ip()."\t".
            $addr['country']."\t".
            'MOBILE'."\t".
            get_user_browser()."\t".
            "登录失败");
        writelog('cplogs', $errorlog);
    }
    die($json->encode($result));
}

/* 退出会员中心 */
elseif ($action == 'logout')
{
    if ((!isset($back_act)|| empty($back_act)) && isset($GLOBALS['_SERVER']['HTTP_REFERER']))
    {
        $back_act = strpos($GLOBALS['_SERVER']['HTTP_REFERER'], 'user.php') ? './index.php' : $GLOBALS['_SERVER']['HTTP_REFERER'];
    }

    require_once(ROOT_PATH.'/plugins/ip/ip.php');
    $ip = new ip();
    $addr = $ip->ip2addr(real_ip());
    $errorlog = (
        time()."\t".
        $_SESSION['user_name']."\t".
        '0'."\t".
        real_ip()."\t".
        $addr['country']."\t".
        'MOBILE'."\t".
        get_user_browser()."\t".
        "退出");
    writelog('cplogs', $errorlog);

    $user->logout();
    $ucdata = empty($user->ucdata)? "" : $user->ucdata;
    // show_message($_LANG['logout'] . $ucdata, array($_LANG['back_up_page'], $_LANG['back_home_lnk']), array($back_act, 'index.php'), 'info');
    ecs_header("Location: index.php\n");
    exit;

}

/* 个人资料页面 */
elseif ($action == 'profile')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');

    $user_info = get_profile($user_id);
    $time=strtotime($user_info['birthday'],' 00:00:00');
    $user_info['year'] = date('Y',$time);
    $user_info['month'] = date('m',$time);
    $user_info['day'] = date('d',$time);

    /* 取出注册扩展字段 */
    $sql = 'SELECT * FROM ' . $ecs->table('reg_fields') . ' WHERE type < 2 AND display = 1 ORDER BY dis_order, id';
    $extend_info_list = $db->getAll($sql);

    $sql = 'SELECT reg_field_id, content ' .
           'FROM ' . $ecs->table('reg_extend_info') .
           " WHERE user_id = $user_id";
    $extend_info_arr = $db->getAll($sql);

    $temp_arr = array();
    foreach ($extend_info_arr AS $val)
    {
        $temp_arr[$val['reg_field_id']] = $val['content'];
    }

    foreach ($extend_info_list AS $key => $val)
    {
        switch ($val['id'])
        {
            case 1:     $extend_info_list[$key]['content'] = $user_info['msn']; break;
            case 2:     $extend_info_list[$key]['content'] = $user_info['qq']; break;
            case 3:     $extend_info_list[$key]['content'] = $user_info['office_phone']; break;
            case 4:     $extend_info_list[$key]['content'] = $user_info['home_phone']; break;
            case 5:     $extend_info_list[$key]['content'] = $user_info['mobile_phone']; break;
            default:    $extend_info_list[$key]['content'] = empty($temp_arr[$val['id']]) ? '' : $temp_arr[$val['id']] ;
        }
    }

    $smarty->assign('extend_info_list', $extend_info_list);
    /* 密码提示问题 */
    $smarty->assign('passwd_questions', $_LANG['passwd_questions']);
    $smarty->assign('profile', $user_info);
    $smarty->assign('title', "个人信息");
    $smarty->display('user_transaction.dwt');
}

/* 修改个人资料的处理 */
elseif ($action == 'act_edit_profile')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');

    $birthday = trim($_POST['birthdayYear']) .'-'. trim($_POST['birthdayMonth']) .'-'.
    trim($_POST['birthdayDay']);
    $email = trim($_POST['email']);
    $other['msn'] = $msn = isset($_POST['extend_field1']) ? trim($_POST['extend_field1']) : '';
    $other['qq'] = $qq = isset($_POST['extend_field2']) ? trim($_POST['extend_field2']) : '';
    $other['office_phone'] = $office_phone = isset($_POST['extend_field3']) ? trim($_POST['extend_field3']) : '';
    $other['home_phone'] = $home_phone = isset($_POST['extend_field4']) ? trim($_POST['extend_field4']) : '';
    $other['mobile_phone'] = $mobile_phone = isset($_POST['extend_field5']) ? trim($_POST['extend_field5']) : '';
    $sel_question = empty($_POST['sel_question']) ? '' : compile_str($_POST['sel_question']);
    $passwd_answer = isset($_POST['passwd_answer']) ? compile_str(trim($_POST['passwd_answer'])) : '';

    /* 更新用户扩展字段的数据 */
    $sql = 'SELECT id FROM ' . $ecs->table('reg_fields') . ' WHERE type = 0 AND display = 1 ORDER BY dis_order, id';   //读出所有扩展字段的id
    $fields_arr = $db->getAll($sql);

    foreach ($fields_arr AS $val)       //循环更新扩展用户信息
    {
        $extend_field_index = 'extend_field' . $val['id'];
        if(isset($_POST[$extend_field_index]))
        {
            $temp_field_content = strlen($_POST[$extend_field_index]) > 100 ? mb_substr(htmlspecialchars($_POST[$extend_field_index]), 0, 99) : htmlspecialchars($_POST[$extend_field_index]);
            $sql = 'SELECT * FROM ' . $ecs->table('reg_extend_info') . "  WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
            if ($db->getOne($sql))      //如果之前没有记录，则插入
            {
                $sql = 'UPDATE ' . $ecs->table('reg_extend_info') . " SET content = '$temp_field_content' WHERE reg_field_id = '$val[id]' AND user_id = '$user_id'";
            }
            else
            {
                $sql = 'INSERT INTO '. $ecs->table('reg_extend_info') . " (`user_id`, `reg_field_id`, `content`) VALUES ('$user_id', '$val[id]', '$temp_field_content')";
            }
            $db->query($sql);
        }
    }

    /* 写入密码提示问题和答案 */
    if (!empty($passwd_answer) && !empty($sel_question))
    {
        $sql = 'UPDATE ' . $ecs->table('users') . " SET `passwd_question`='$sel_question', `passwd_answer`='$passwd_answer'  WHERE `user_id`='" . $_SESSION['user_id'] . "'";
        $db->query($sql);
    }

    if (!empty($office_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $office_phone ) )
    {
        show_message($_LANG['passport_js']['office_phone_invalid']);
    }
    if (!empty($home_phone) && !preg_match( '/^[\d|\_|\-|\s]+$/', $home_phone) )
    {
         show_message($_LANG['passport_js']['home_phone_invalid']);
    }
    if (!is_email($email))
    {
        show_message($_LANG['msg_email_format']);
    }
    if (!empty($msn) && !is_email($msn))
    {
         show_message($_LANG['passport_js']['msn_invalid']);
    }
    if (!empty($qq) && !preg_match('/^\d+$/', $qq))
    {
         show_message($_LANG['passport_js']['qq_invalid']);
    }
    if (!empty($mobile_phone) && !preg_match('/^[\d-\s]+$/', $mobile_phone))
    {
        show_message($_LANG['passport_js']['mobile_phone_invalid']);
    }


    $profile  = array(
        'user_id'  => $user_id,
        'email'    => isset($_POST['email']) ? trim($_POST['email']) : '',
        'sex'      => isset($_POST['sex'])   ? intval($_POST['sex']) : 0,
        'birthday' => $birthday,
        'other'    => isset($other) ? $other : array()
        );


    if (edit_profile($profile))
    {
        show_message($_LANG['edit_profile_success'], $_LANG['profile_lnk'], 'user.php?act=profile', 'info');
    }
    else
    {
        if ($user->error == ERR_EMAIL_EXISTS)
        {
            $msg = sprintf($_LANG['email_exist'], $profile['email']);
        }
        else
        {
            $msg = $_LANG['edit_profile_failed'];
        }
        show_message($msg, '', '', 'info');
    }
}

/* 密码找回-->修改密码界面 */
elseif ($action == 'get_password')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');

    if (isset($_GET['code']) && isset($_GET['uid'])) //从邮件处获得的act
    {
        $code = trim($_GET['code']);
        $uid  = intval($_GET['uid']);

        /* 判断链接的合法性 */
        $user_info = $user->get_profile_by_id($uid);
        if (empty($user_info) || ($user_info && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) != $code))
        {
            show_message($_LANG['parm_error'], $_LANG['back_home_lnk'], './', 'info');
        }

        $smarty->assign('uid',    $uid);
        $smarty->assign('code',   $code);
        $smarty->assign('action', 'reset_password');
        $smarty->display('user_passport.dwt');
    }
    else
    {
        //显示用户名和email表单
        $smarty->display('user_passport.dwt');
    }
}

/* 密码找回-->输入用户名界面 */
elseif ($action == 'qpassword_name')
{
    //显示输入要找回密码的账号表单
    $smarty->display('user_passport.dwt');
}

/* 密码找回-->根据注册用户名取得密码提示问题界面 */
elseif ($action == 'get_passwd_question')
{
    if (empty($_POST['user_name']))
    {
        show_message($_LANG['no_passwd_question'], $_LANG['back_home_lnk'], './', 'info');
    }
    else
    {
        $user_name = trim($_POST['user_name']);
    }

    //取出会员密码问题和答案
    $sql = 'SELECT user_id, user_name, passwd_question, passwd_answer FROM ' . $ecs->table('users') . " WHERE user_name = '" . $user_name . "'";
    $user_question_arr = $db->getRow($sql);

    //如果没有设置密码问题，给出错误提示
    if (empty($user_question_arr['passwd_answer']))
    {
        show_message($_LANG['no_passwd_question'], $_LANG['back_home_lnk'], './', 'info');
    }

    $_SESSION['temp_user'] = $user_question_arr['user_id'];  //设置临时用户，不具有有效身份
    $_SESSION['temp_user_name'] = $user_question_arr['user_name'];  //设置临时用户，不具有有效身份
    $_SESSION['passwd_answer'] = $user_question_arr['passwd_answer'];   //存储密码问题答案，减少一次数据库访问

    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        $GLOBALS['smarty']->assign('enabled_captcha', 1);
        $GLOBALS['smarty']->assign('rand', mt_rand());
    }

    $smarty->assign('passwd_question', $_LANG['passwd_questions'][$user_question_arr['passwd_question']]);
    $smarty->display('user_passport.dwt');
}

/* 密码找回-->根据提交的密码答案进行相应处理 */
elseif ($action == 'check_answer')
{
    $captcha = intval($_CFG['captcha']);
    if (($captcha & CAPTCHA_LOGIN) && (!($captcha & CAPTCHA_LOGIN_FAIL) || (($captcha & CAPTCHA_LOGIN_FAIL) && $_SESSION['login_fail'] > 2)) && gd_version() > 0)
    {
        if (empty($_POST['captcha']))
        {
            show_message($_LANG['invalid_captcha'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'error');
        }

        /* 检查验证码 */
        include_once('includes/cls_captcha.php');

        $validator = new captcha();
        $validator->session_word = 'captcha_login';
        if (!$validator->check_word($_POST['captcha']))
        {
            show_message($_LANG['invalid_captcha'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'error');
        }
    }

    if (empty($_POST['passwd_answer']) || $_POST['passwd_answer'] != $_SESSION['passwd_answer'])
    {
        show_message($_LANG['wrong_passwd_answer'], $_LANG['back_retry_answer'], 'user.php?act=qpassword_name', 'info');
    }
    else
    {
        $_SESSION['user_id'] = $_SESSION['temp_user'];
        $_SESSION['user_name'] = $_SESSION['temp_user_name'];
        unset($_SESSION['temp_user']);
        unset($_SESSION['temp_user_name']);
        $smarty->assign('uid',    $_SESSION['user_id']);
        $smarty->assign('action', 'reset_password');
        $smarty->display('user_passport.dwt');
    }
}

/* 发送密码修改确认邮件 */
elseif ($action == 'send_pwd_email')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');

    /* 初始化会员用户名和邮件地址 */
    $user_name = !empty($_POST['user_name']) ? trim($_POST['user_name']) : '';
    $email     = !empty($_POST['email'])     ? trim($_POST['email'])     : '';

    //用户名和邮件地址是否匹配
    $user_info = $user->get_user_info($user_name);

    if ($user_info && $user_info['email'] == $email)
    {
        //生成code
         //$code = md5($user_info[0] . $user_info[1]);

        $code = md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']);
        //发送邮件的函数
        if (send_pwd_email($user_info['user_id'], $user_name, $email, $code))
        {
            show_message($_LANG['send_success'] . $email, $_LANG['back_home_lnk'], './', 'info');
        }
        else
        {
            //发送邮件出错
            show_message($_LANG['fail_send_password'], $_LANG['back_page_up'], './', 'info');
        }
    }
    else
    {
        //用户名与邮件地址不匹配
        show_message($_LANG['username_no_email'], $_LANG['back_page_up'], '', 'info');
    }
}

/* 重置新密码 */
elseif ($action == 'reset_password')
{
    //显示重置密码的表单
    $smarty->display('user_passport.dwt');
}

/* 修改会员密码 */
elseif ($action == 'act_edit_password')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_passport.php');

    $old_password = isset($_POST['old_password']) ? trim($_POST['old_password']) : null;
    $new_password = isset($_POST['new_password']) ? trim($_POST['new_password']) : '';
    $user_id      = isset($_POST['uid'])  ? intval($_POST['uid']) : $user_id;
    $code         = isset($_POST['code']) ? trim($_POST['code'])  : '';

    if (strlen($new_password) < 6)
    {
        show_message($_LANG['passport_js']['password_shorter']);
    }

    $user_info = $user->get_profile_by_id($user_id); //论坛记录

    if (($user_info && (!empty($code) && md5($user_info['user_id'] . $_CFG['hash_code'] . $user_info['reg_time']) == $code)) || ($_SESSION['user_id']>0 && $_SESSION['user_id'] == $user_id && $user->check_user($_SESSION['user_name'], $old_password)))
    {

        if ($user->edit_user(array('username'=> (empty($code) ? $_SESSION['user_name'] : $user_info['user_name']), 'old_password'=>$old_password, 'password'=>$new_password), empty($code) ? 0 : 1))
        {
            $sql="UPDATE ".$ecs->table('users'). "SET `ec_salt`='0' WHERE user_id= '".$user_id."'";
            $db->query($sql);
            $user->logout();
            show_message($_LANG['edit_password_success'], $_LANG['relogin_lnk'], 'user.php?act=login', 'info');
        }
        else
        {
            show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info');
        }
    }
    else
    {
        show_message($_LANG['edit_password_failure'], $_LANG['back_page_up'], '', 'info');
    }

}

/* 添加艺晨劵 */
elseif ($action == 'act_add_bonus')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'mobile/includes/cls_json.php');
    $bonus_id = isset($_REQUEST['bonus_id']) ? json_str_iconv($_REQUEST['bonus_id']) : '';
        $json   = new JSON;
    if (add_bonus($user_id, $bouns_sn))
    {
    $result["message"] = "添加成功";
    echo $json->encode($result);
    exit;
    }
    else
    {
    $result["message"] = "序列号错误";
    echo $json->encode($result);
    exit;
    }
}

/* 查看订单列表 */
elseif ($action == 'order_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_payment.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('order_info'). " WHERE join_id=0 AND user_id = '$user_id'");
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page ,15);
    $_SESSION['order_count_type'] = $count_type;
    $smarty->assign('order_count_type', $count_type);
    $orders = get_user_orders($user_id, $pager['size'], $pager['start']);
    foreach ($orders as $key => $value) {
         $orders[$key]["son"]=order_goods($value["order_id"]);
    }
    $merge  = get_user_merge($user_id);
    $count = get_user_count($user_id);
    $back_url = "user.php";
    $smarty->assign('count', $count);
    $smarty->assign('merge',  $merge);
    $smarty->assign('pager',  $pager);
    $smarty->assign('orders', $orders);
    $smarty->assign('back_url',  $back_url);
    $smarty->display('user_order_list.dwt');
}
/* 查看订单详情 */
elseif ($action == 'order_detail')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_payment.php');
    // include_once(ROOT_PATH . 'mobile/includes/lib_order.php');
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    /* 订单详情 */
    $order = get_order_detail($order_id, $user_id);

    if ($order === false)
    {

        ecs_header("Location: user.php?act=order_list\n");
        exit;
    }

    /* 是否显示添加到购物车 */
    if ($order['extension_code'] != 'group_buy' && $order['extension_code'] != 'exchange_goods')
    {
        $smarty->assign('allow_to_cart', 1);
    }

    /* 订单商品 */
    $goods_lists = order_goods($order_id);

    foreach ($goods_lists AS $key => $value)
    {
        $goods_list[$key]=$value;
        $goods_list[$key]['market_price'] = price_format($value['market_price'], false);
        $goods_list[$key]['goods_price']  = price_format($value['goods_price'], false);
        $goods_list[$key]['subtotal']     = price_format($value['subtotal'], false);
        if($value['extension_code']=='libao'){
            if($value['parent_id'] && $value['goods_id'] == 0){
                $libaoInfo[$value['parent_id']] = $value;
            }else{
                $libaoGoods[$value['parent_id']][] = $value;
                unset($goods_list[$key]);
            }
        }
    }
    /* 根据不同支付方式判断其状态 */
    if($order['pay_id'] == 1) {
        if($order['pay_status'] == 0){
            $order['order_status'] = '未付款';
        }elseif($order['shipping_status'] == 0 && $order['order_status'] == 1){
            $order['order_status'] = '正在发货';
        }elseif($order['shipping_status'] == 1){
            $order['order_status'] = '已发货';
        }elseif($order['shipping_status'] == 2){
            $order['order_status'] = '交易成功';
        }
    }elseif($order['pay_id'] == 3){
        if($order['order_status'] == 0){
            $order['order_status'] = '待发货';
        }elseif($order['shipping_status'] == 0 && $order['order_status'] == 1){
            $order['order_status'] = '正在发货';
        }elseif($order['shipping_status'] == 1){
            $order['order_status'] = '已发货';
        }elseif($order['shipping_status'] == 2){
            $order['order_status'] = '交易成功';
        }
    }
    /* 订单 支付 配送 状态语言项 */
    $order['pay_status'] = $_LANG['ps'][$order['pay_status']];
    $order['shipping_status'] = $_LANG['ss'][$order['shipping_status']];
    $order['add_time']=date('Y.m.d',$order['add_time']);
    $order['addr']=selectaddress($order['province'])." ".selectaddress($order['city'])." ".selectaddress($order['district']);
    $smarty->assign('order',      $order);
    $smarty->assign('back_url',      'user.php?act=order_list');
    $smarty->assign('premiums_goods', $premiums_goods);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('user_order_detail.dwt');
}
/* 取消订单 */
elseif ($action == 'cancel_order')
{
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    include_once(ROOT_PATH . 'includes/lib_order.php');
    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $order=order_info($order_id);
    $area_id=is_buy($order);
    $goods_list = order_goods($order_id);

    if (cancel_order($order_id, $user_id))
    {
        ecs_header("Location: user.php?act=order_list\n");
        exit;
    }
    else
    {
        $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list');
    }
}

/* 收货地址列表界面*/
elseif ($action == 'address_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang',  $_LANG);

    /* 取得国家列表、商店所在国家、商店所在国家的省列表 */
    $smarty->assign('country_list',       get_regions());
    $smarty->assign('shop_province_list', get_regions(1, $_CFG['shop_country']));

    /* 获得用户所有的收货人信息 */
    $consignee_list = get_consignee_list($_SESSION['user_id']);
    if($consignee_list){
        $count=count($consignee);
        foreach ($consignee_list AS $region_id => $consignee)
        {
            $consignee_list [$region_id]['region']    = selectaddress($consignee['province']).selectaddress($consignee['city']).selectaddress($consignee['district']);
        }
        $smarty->assign('consignee_list', $consignee_list);
    }


    /* 获取默认收货ID */
    $address_id  = $db->getOne("SELECT address_id FROM " .$ecs->table('users'). " WHERE user_id='$user_id'");
    //赋值于模板
    $smarty->assign('real_goods_count', 1);
    $smarty->assign('shop_country',     $_CFG['shop_country']);
    $smarty->assign('shop_province',    get_regions(1, $_CFG['shop_country']));
    $smarty->assign('count',    $count);
    $smarty->assign('address',          $address_id);
    $smarty->assign('currency_format',  $_CFG['currency_format']);
    $smarty->assign('integral_scale',   $_CFG['integral_scale']);
    $smarty->assign('name_of_region',   array($_CFG['name_of_region_1'], $_CFG['name_of_region_2'], $_CFG['name_of_region_3'], $_CFG['name_of_region_4']));
    $smarty->display('user_transaction.dwt');
}
/*AJAX设定默认地址*/
elseif ($action == 'set_default') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $address_id = $_POST['address_id'];
    $sql="UPDATE ".$ecs->table('users')." SET address_id='$address_id'".
    " WHERE user_id=".$user_id;
    $up_address=$db->query($sql);
    if($up_address){
        echo $json->encode("修改成功");
    }
    else{
        echo $json->encode("修改错误");
    }
}
/*添加、修改收货地址页面*/
elseif ($action == 'address_add') {
$smarty->display('user_transaction.dwt');
}
/*修改收货地址页面*/
elseif ($action == 'address_up') {
    $address_id=$_REQUEST['address_id'];

    if(empty($address_id)){
       ecs_header("Location: index.php");
    }
    else{
        $sql="SELECT * FROM ".$ecs->table('user_address')."WHERE address_id=".$address_id;
        $consignee=$db->getRow($sql);
        $consignee['region'] = selectaddress($consignee['province']).selectaddress($consignee['city']).selectaddress($consignee['district']);
        $consignee['province_name']=selectaddress($consignee['province']);
        $consignee['city_name']=selectaddress($consignee['city']);
        $consignee['district_name']=selectaddress($consignee['district']);



    }
    // 默认省市区列表
    $province_list = get_regions(1, 1);
    $city_list     = get_regions(2, $consignee['province']);
    $district_list = get_regions(3, $consignee['city']);
    $smarty->assign('province_list', $province_list);
    $smarty->assign('city_list',     $city_list);
    $smarty->assign('district_list', $district_list);
    $smarty->assign('consignee', $consignee);
    $smarty->display('user_transaction.dwt');
}





/* 添加/编辑收货地址的处理 */
elseif ($action == 'act_edit_address')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    include_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    $smarty->assign('lang', $_LANG);
    $count =  count(get_consignee_list($_SESSION['user_id']));
    $count = !empty($count)?$count:1;
    $address = array(
        'num'        => $count,
        'user_id'    => $user_id,
        'country'    => isset($_POST['country'])   ? intval($_POST['country'])  : 1,
        'province'   => isset($_POST['province'])  ? intval($_POST['province']) : 0,
        'city'       => isset($_POST['city'])      ? intval($_POST['city'])     : 0,
        'district'   => isset($_POST['district'])  ? intval($_POST['district']) : 0,
        'address'    => isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
        'consignee'  => isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
        'mobile'     => isset($_POST['mobile'])    ? compile_str(make_semiangle(trim($_POST['mobile']))) : '',
        );
    if(in_array("",$address)){
        show_message("你输入的地址信息有误");
        exit;
    }
    $address['address_id']=intval($_POST['address_id']);
    if (update_address($address))
    {
        ecs_header("Location: user.php?act=address_list\n");
    }
}

/* 删除收货地址 */
elseif ($action == 'drop_consignee')
{
    include_once('includes/lib_transaction.php');

    $consignee_id = intval($_GET['id']);

    if (drop_consignee($consignee_id))
    {
        ecs_header("Location: user.php?act=address_list\n");
        exit;
    }
    else
    {
        show_message($_LANG['del_address_false']);
    }
}

/* 我的全免费计划 */
elseif ($action == 'freeplan'){

    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    /* 查询画材全免计划报名资料 */
    $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('user_freeplan') .
        " WHERE user_id = $user_id";
    $freeplan_info = $GLOBALS['db']->getRow($sql);

    if( !$freeplan_info ){
        header('location:freeplan.php');
    }

    /* 考上美院成功率 */
    $percentage = get_this_month_percentage($user_id);

    /* 当月消费记录 */
    $cost = get_this_month_goods($user_id);

    /* 为您推荐 */
    $recommend = get_reco_goods();

    $smarty->assign('freeplan_info', $freeplan_info);
    $smarty->assign('percentage', $percentage);
    $smarty->assign('cost', $cost);
    $smarty->assign('recommend', $recommend);
    $smarty->assign('top_title',  '我的圆梦美院');
    $smarty->display('user_freeplan.dwt');
}

/* 我的全免费计划 */
elseif ($action == 'freeplan_info'){
    /* 查询画材全免计划报名资料 */
    $sql = 'SELECT * FROM ' .$GLOBALS['ecs']->table('user_freeplan') .
        " WHERE user_id = $user_id";
    $freeplan_info = $GLOBALS['db']->getRow($sql);
    $freeplan_info['idcardnumber'] = substr($freeplan_info['idcardnumber'],0,4).'**********'.substr($freeplan_info['idcardnumber'],-4);

    /* 把就读学校所在地区的id取出来 */
    $addr_ids = $freeplan_info['schooladdr'];
    $addr_ids = substr($addr_ids, 2);     // 把“中国”去掉
    $sql = "SELECT region_name FROM " .$GLOBALS['ecs']->table('region') .
        " WHERE region_id IN ( $addr_ids )";
    $address = $GLOBALS['db']->getAll($sql);
    // 把地址重新组合
    foreach ($address as $key => $value) {
        $addr .= $value['region_name'];
    }
        /*划分录入时间段*/
    $time_num = 1;
    $time = time();

    /*测试*/
    if ($time<1435593600) {
        $time_num =1;
    }
    elseif ($time>1435593600&&$time<1436889600) {
        $time_num =2;
    }
    elseif ($time>1436889600&&$time<1439136000) {
        $time_num =3;
    }
    elseif ($time>1439136000) {
        $time_num =4;
    }




    $smarty->assign('time_num', $time_num);
    $smarty->assign('freeplan_info', $freeplan_info);
    $smarty->assign('addr', $addr);
    $smarty->assign('top_title',  '我的资料');
    $smarty->display('user_freeplan.dwt');
}

/* 显示收藏商品列表 */
elseif ($action == 'collection_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('collect_goods').
                                " WHERE user_id='$user_id' ORDER BY add_time DESC");

    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);
    $smarty->assign('pager', $pager);
    $smarty->assign('goods_list', get_collection_goods($user_id, $pager['size'], $pager['start']));

    $smarty->assign('url',        $ecs->url());
    $lang_list = array(
        'UTF8'   => $_LANG['charset']['utf8'],
        'GB2312' => $_LANG['charset']['zh_cn'],
        'BIG5'   => $_LANG['charset']['zh_tw'],
    );
    // 重组收藏商品数组
    foreach (get_collection_goods($user_id, $pager['size'], $pager['start']) as $key => $value) {
    $list["id"]=$value["rec_id"];
    $list["is_attention"]=$value["is_attention"];
    $list["goods_id"]=$value["goods_id"];
    $list["name"]=$value["goods_name"];
    $list["price"]=$value["shop_price"];
    $list["url"]=$value["url"];
    $list["promote_price"]=$value["promote_price"];
    $pic=get_goods_info($value["goods_id"]);
    $list["pic"]= $pic["goods_thumb"];
    $list["brand"]=$pic["goods_brand"];
    $goods_list[$key]=$list;
    }


    $smarty->assign('goods_list',  $goods_list);
    $smarty->assign('lang_list',  $lang_list);
    $smarty->assign('user_id',  $user_id);
    $smarty->assign('title',  '我的收藏');
    $smarty->display('user_clips.dwt');
}

/* 删除收藏的商品 */
elseif ($action == 'delete_collection')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $collection_id = isset($_GET['collection_id']) ? intval($_GET['collection_id']) : 0;

    if ($collection_id > 0)
    {
        $db->query('DELETE FROM ' .$ecs->table('collect_goods'). " WHERE rec_id='$collection_id' AND user_id ='$user_id'" );
    }

    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}

/* 添加关注商品 */
elseif ($action == 'add_to_attention')
{
    $rec_id = (int)$_GET['rec_id'];
    if ($rec_id)
    {
        $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 1 WHERE rec_id='$rec_id' AND user_id ='$user_id'" );
    }
    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}
/* 取消关注商品 */
elseif ($action == 'del_attention')
{
    $rec_id = (int)$_GET['rec_id'];
    if ($rec_id)
    {
        $db->query('UPDATE ' .$ecs->table('collect_goods'). "SET is_attention = 0 WHERE rec_id='$rec_id' AND user_id ='$user_id'" );
    }
    ecs_header("Location: user.php?act=collection_list\n");
    exit;
}
/* 显示留言列表 */
elseif ($action == 'message_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
    $order_info = array();

    /* 获取用户留言的数量 */
    if ($order_id)
    {
        $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback').
                " WHERE parent_id = 0 AND order_id = '$order_id' AND user_id = '$user_id'";
        $order_info = $db->getRow("SELECT * FROM " . $ecs->table('order_info') . " WHERE order_id = '$order_id' AND user_id = '$user_id'");
        $order_info['url'] = 'user.php?act=order_detail&order_id=' . $order_id;
    }
    else
    {
        $sql = "SELECT COUNT(*) FROM " .$ecs->table('feedback').
           " WHERE parent_id = 0 AND user_id = '$user_id' AND user_name = '" . $_SESSION['user_name'] . "' AND order_id=0";
    }

    $record_count = $db->getOne($sql);
    $act = array('act' => $action);

    if ($order_id != '')
    {
        $act['order_id'] = $order_id;
    }

    $pager = get_pager('user.php', $act, $record_count, $page, 5);

    $smarty->assign('message_list', get_message_list($user_id, $_SESSION['user_name'], $pager['size'], $pager['start'], $order_id));
    $smarty->assign('pager',        $pager);
    $smarty->assign('order_info',   $order_info);
    $smarty->display('user_clips.dwt');
}

/* 显示评论列表 */
elseif ($action == 'comment_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    /* 获取用户留言的数量 */
    $sql = "SELECT COUNT(*) FROM " .$ecs->table('comment').
           " WHERE parent_id = 0 AND user_id = '$user_id'";
    $record_count = $db->getOne($sql);
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page, 5);

    $smarty->assign('comment_list', get_comment_list($user_id, $pager['size'], $pager['start']));
    $smarty->assign('pager',        $pager);
    $smarty->display('user_clips.dwt');
}

/* 添加我的留言 */
elseif ($action == 'act_add_message')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $message = array(
        'user_id'     => $user_id,
        'user_name'   => $_SESSION['user_name'],
        'user_email'  => $_SESSION['email'],
        'msg_type'    => isset($_POST['msg_type']) ? intval($_POST['msg_type'])     : 0,
        'msg_title'   => isset($_POST['msg_title']) ? trim($_POST['msg_title'])     : '',
        'msg_content' => isset($_POST['msg_content']) ? trim($_POST['msg_content']) : '',
        'order_id'=>empty($_POST['order_id']) ? 0 : intval($_POST['order_id']),
        'upload'      => (isset($_FILES['message_img']['error']) && $_FILES['message_img']['error'] == 0) || (!isset($_FILES['message_img']['error']) && isset($_FILES['message_img']['tmp_name']) && $_FILES['message_img']['tmp_name'] != 'none')
         ? $_FILES['message_img'] : array()
     );

    if (add_message($message))
    {
        show_message($_LANG['add_message_success'], $_LANG['message_list_lnk'], 'user.php?act=message_list&order_id=' . $message['order_id'],'info');
    }
    else
    {
        $err->show($_LANG['message_list_lnk'], 'user.php?act=message_list');
    }
}

/* 标签云列表 */
elseif ($action == 'tag_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $good_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

    $smarty->assign('tags',      get_user_tags($user_id));
    $smarty->assign('tags_from', 'user');
    $smarty->display('user_clips.dwt');
}

/* 删除标签云的处理 */
elseif ($action == 'act_del_tag')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $tag_words = isset($_GET['tag_words']) ? trim($_GET['tag_words']) : '';
    delete_tag($tag_words, $user_id);

    ecs_header("Location: user.php?act=tag_list\n");
    exit;

}

/* 显示缺货登记列表 */
elseif ($action == 'booking_list')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;

    /* 获取缺货登记的数量 */
    $sql = "SELECT COUNT(*) " .
            "FROM " .$ecs->table('booking_goods'). " AS bg, " .
                     $ecs->table('goods') . " AS g " .
            "WHERE bg.goods_id = g.goods_id AND user_id = '$user_id'";
    $record_count = $db->getOne($sql);
    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);

    $smarty->assign('booking_list', get_booking_list($user_id, $pager['size'], $pager['start']));
    $smarty->assign('pager',        $pager);
    $smarty->display('user_clips.dwt');
}
/* 添加缺货登记页面 */
elseif ($action == 'add_booking')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $goods_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($goods_id == 0)
    {
        show_message($_LANG['no_goods_id'], $_LANG['back_page_up'], '', 'error');
    }

    /* 根据规格属性获取货品规格信息 */
    $goods_attr = '';
    if ($_GET['spec'] != '')
    {
        $goods_attr_id = $_GET['spec'];

        $attr_list = array();
        $sql = "SELECT a.attr_name, g.attr_value " .
                "FROM " . $ecs->table('goods_attr') . " AS g, " .
                    $ecs->table('attribute') . " AS a " .
                "WHERE g.attr_id = a.attr_id " .
                "AND g.goods_attr_id " . db_create_in($goods_attr_id);
        $res = $db->query($sql);
        while ($row = $db->fetchRow($res))
        {
            $attr_list[] = $row['attr_name'] . ': ' . $row['attr_value'];
        }
        $goods_attr = join(chr(13) . chr(10), $attr_list);
    }
    $smarty->assign('goods_attr', $goods_attr);

    $smarty->assign('info', get_goodsinfo($goods_id));
    $smarty->display('user_clips.dwt');

}

/* 添加缺货登记的处理 */
elseif ($action == 'act_add_booking')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $booking = array(
        'goods_id'     => isset($_POST['id'])      ? intval($_POST['id'])     : 0,
        'goods_amount' => isset($_POST['number'])  ? intval($_POST['number']) : 0,
        'desc'         => isset($_POST['desc'])    ? trim($_POST['desc'])     : '',
        'linkman'      => isset($_POST['linkman']) ? trim($_POST['linkman'])  : '',
        'email'        => isset($_POST['email'])   ? trim($_POST['email'])    : '',
        'tel'          => isset($_POST['tel'])     ? trim($_POST['tel'])      : '',
        'booking_id'   => isset($_POST['rec_id'])  ? intval($_POST['rec_id']) : 0
    );

    // 查看此商品是否已经登记过
    $rec_id = get_booking_rec($user_id, $booking['goods_id']);
    if ($rec_id > 0)
    {
        show_message($_LANG['booking_rec_exist'], $_LANG['back_page_up'], '', 'error');
    }

    if (add_booking($booking))
    {
        show_message($_LANG['booking_success'], $_LANG['back_booking_list'], 'user.php?act=booking_list',
        'info');
    }
    else
    {
        $err->show($_LANG['booking_list_lnk'], 'user.php?act=booking_list');
    }
}

/* 删除缺货登记 */
elseif ($action == 'act_del_booking')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_clips.php');

    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id == 0 || $user_id == 0)
    {
        ecs_header("Location: user.php?act=booking_list\n");
        exit;
    }

    $result = delete_booking($id, $user_id);
    if ($result)
    {
        ecs_header("Location: user.php?act=booking_list\n");
        exit;
    }
}

/* 确认收货 */
elseif ($action == 'affirm_received')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');

    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    if (affirm_received($order_id, $user_id))
    {
        ecs_header("Location: user.php?act=order_list\n");
        exit;
    }
    else
    {
        $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list');
    }
}

/* 会员退款申请界面 */

/* 添加标签(ajax) */
elseif ($action == 'add_tag')
{
    include_once('includes/cls_json.php');
    include_once('includes/lib_clips.php');

    $result = array('error' => 0, 'message' => '', 'content' => '');
    $id     = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $tag    = isset($_POST['tag']) ? json_str_iconv(trim($_POST['tag'])) : '';

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['tag_anonymous'];
    }
    else
    {
        add_tag($id, $tag); // 添加tag
        clear_cache_files('goods'); // 删除缓存

        /* 重新获得该商品的所有缓存 */
        $arr = get_tags($id);

        foreach ($arr AS $row)
        {
            $result['content'][] = array('word' => htmlspecialchars($row['tag_words']), 'count' => $row['tag_count']);
        }
    }

    $json = new JSON;

    echo $json->encode($result);
    exit;
}

/* 添加收藏商品(ajax) */
elseif ($action == 'collect')
{
    include_once(ROOT_PATH .'mobile/includes/cls_json.php');
    $json = new JSON();
    $result = array('error' => 0, 'message' => '');
    $goods_id = $_GET['id'];

    if (!isset($_SESSION['user_id']) || $_SESSION['user_id'] == 0)
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }
    else
    {
        /* 检查是否已经存在于用户的收藏夹 */
        $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('collect_goods') .
            " WHERE user_id='$_SESSION[user_id]' AND goods_id = '$goods_id'";
        if ($GLOBALS['db']->GetOne($sql) > 0)
        {
            $result['error'] = 1;
            $result['message'] = $GLOBALS['_LANG']['collect_existed'];
            die($json->encode($result));
        }
        else
        {
            $time = gmtime();
            $sql = "INSERT INTO " .$GLOBALS['ecs']->table('collect_goods'). " (user_id, goods_id, add_time)" .
                    "VALUES ('$_SESSION[user_id]', '$goods_id', '$time')";

            if ($GLOBALS['db']->query($sql) === false)
            {
                $result['error'] = 1;
                $result['message'] = $GLOBALS['db']->errorMsg();
                die($json->encode($result));
            }
            else
            {
                $result['error'] = 0;
                $result['message'] = $GLOBALS['_LANG']['collect_success'];
                die($json->encode($result));
            }
        }
    }
}

/* 删除留言 */
elseif ($action == 'del_msg')
{
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);

    if ($id > 0)
    {
        $sql = 'SELECT user_id, message_img FROM ' .$ecs->table('feedback'). " WHERE msg_id = '$id' LIMIT 1";
        $row = $db->getRow($sql);
        if ($row && $row['user_id'] == $user_id)
        {
            /* 验证通过，删除留言，回复，及相应文件 */
            if ($row['message_img'])
            {
                @unlink(ROOT_PATH . DATA_DIR . '/feedbackimg/'. $row['message_img']);
            }
            $sql = "DELETE FROM " .$ecs->table('feedback'). " WHERE msg_id = '$id' OR parent_id = '$id'";
            $db->query($sql);
        }
    }
    ecs_header("Location: user.php?act=message_list&order_id=$order_id\n");
    exit;
}

/* 删除评论 */
elseif ($action == 'del_cmt')
{
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    if ($id > 0)
    {
        $sql = "DELETE FROM " .$ecs->table('comment'). " WHERE comment_id = '$id' AND user_id = '$user_id'";
        $db->query($sql);
    }
    ecs_header("Location: user.php?act=comment_list\n");
    exit;
}


/* 将指定订单中商品添加到购物车 */
elseif ($action == 'return_to_cart')
{
    include_once(ROOT_PATH .'mobile/includes/cls_json.php');
    include_once(ROOT_PATH .'mobile/includes/lib_transaction.php');
    $json = new JSON();
    $result = array('error' => 0, 'message' => '', 'content' => '');
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    if ($order_id == 0)
    {
        $result['error']   = 1;
        $result['message'] = $_LANG['order_id_empty'];
        die($json->encode($result));
    }

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }

    /* 检查订单是否属于该用户 */
    $order_user = $db->getOne("SELECT user_id FROM " .$ecs->table('order_info'). " WHERE order_id = '$order_id'");
    if (empty($order_user))
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['order_exist'];
        die($json->encode($result));
    }
    else
    {
        if ($order_user != $user_id)
        {
            $result['error'] = 1;
            $result['message'] = $_LANG['no_priv'];
            die($json->encode($result));
        }
    }

    $message = return_to_cart($order_id);

    if ($message === true)
    {
        $result['error'] = 0;
        $result['message'] = '加入购物车成功';
        die($json->encode($result));
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['order_exist'];
        die($json->encode($result));
    }

}



/* 保存收货地址 */
elseif ($action == 'save_order_address')
{
    include_once(ROOT_PATH .'mobile/includes/lib_transaction.php');

    $address = array(
        'consignee' => isset($_POST['consignee']) ? compile_str(trim($_POST['consignee']))  : '',
        'email'     => isset($_POST['email'])     ? compile_str(trim($_POST['email']))      : '',
        'address'   => isset($_POST['address'])   ? compile_str(trim($_POST['address']))    : '',
        'zipcode'   => isset($_POST['zipcode'])   ? compile_str(make_semiangle(trim($_POST['zipcode']))) : '',
        'tel'       => isset($_POST['tel'])       ? compile_str(trim($_POST['tel']))        : '',
        'mobile'    => isset($_POST['mobile'])    ? compile_str(trim($_POST['mobile']))     : '',
        'sign_building' => isset($_POST['sign_building']) ? compile_str(trim($_POST['sign_building'])) : '',
        'best_time' => isset($_POST['best_time']) ? compile_str(trim($_POST['best_time']))  : '',
        'order_id'  => isset($_POST['order_id'])  ? intval($_POST['order_id']) : 0
        );
    if (save_order_address($address, $user_id))
    {
        ecs_header('Location: user.php?act=order_detail&order_id=' .$address['order_id']. "\n");
        exit;
    }
    else
    {
        $err->show($_LANG['order_list_lnk'], 'user.php?act=order_list');
    }
}

/* 我的红包列表 */
elseif ($action == 'bonus')
{
    include_once(ROOT_PATH .'mobile/includes/lib_transaction.php');

    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('user_bonus'). " WHERE user_id = '$user_id'");

    $pager = get_pager('user.php', array('act' => $action), $record_count, $page);
    $bonus = get_user_bouns_list($user_id, $pager['size'], $pager['start']);

    $smarty->assign('pager', $pager);
    $smarty->assign('bonus', $bonus);
    $smarty->assign('title', '艺晨卷');
    $smarty->display('user_transaction.dwt');
}




// 用户推荐页面
elseif ($action == 'affiliate')
{
    $goodsid = intval(isset($_REQUEST['goodsid']) ? $_REQUEST['goodsid'] : 0);
    if(empty($goodsid))
    {
        //我的推荐页面

        $page       = !empty($_REQUEST['page'])  && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;
        $size       = !empty($_CFG['page_size']) && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;

        empty($affiliate) && $affiliate = array();

        if(empty($affiliate['config']['separate_by']))
        {
            //推荐注册分成
            $affdb = array();
            $num = count($affiliate['item']);
            $up_uid = "'$user_id'";
            $all_uid = "'$user_id'";
            for ($i = 1 ; $i <=$num ;$i++)
            {
                $count = 0;
                if ($up_uid)
                {
                    $sql = "SELECT user_id FROM " . $ecs->table('users') . " WHERE parent_id IN($up_uid)";
                    $query = $db->query($sql);
                    $up_uid = '';
                    while ($rt = $db->fetch_array($query))
                    {
                        $up_uid .= $up_uid ? ",'$rt[user_id]'" : "'$rt[user_id]'";
                        if($i < $num)
                        {
                            $all_uid .= ", '$rt[user_id]'";
                        }
                        $count++;
                    }
                }
                $affdb[$i]['num'] = $count;
                $affdb[$i]['point'] = $affiliate['item'][$i-1]['level_point'];
                $affdb[$i]['money'] = $affiliate['item'][$i-1]['level_money'];
            }
            $smarty->assign('affdb', $affdb);

            $sqlcount = "SELECT count(*) FROM " . $ecs->table('order_info') . " o".
        " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id".
        " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" .
        " WHERE o.user_id > 0 AND (u.parent_id IN ($all_uid) AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)";

            $sql = "SELECT o.*, a.log_id, a.user_id as suid,  a.user_name as auser, a.money, a.point, a.separate_type FROM " . $ecs->table('order_info') . " o".
                    " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id".
                    " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" .
        " WHERE o.user_id > 0 AND (u.parent_id IN ($all_uid) AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)".
                    " ORDER BY order_id DESC" ;

            /*
                SQL解释：

                订单、用户、分成记录关联
                一个订单可能有多个分成记录

                1、订单有效 o.user_id > 0
                2、满足以下之一：
                    a.直接下线的未分成订单 u.parent_id IN ($all_uid) AND o.is_separate = 0
                        其中$all_uid为该ID及其下线(不包含最后一层下线)
                    b.全部已分成订单 a.user_id = '$user_id' AND o.is_separate > 0

            */

            $affiliate_intro = nl2br(sprintf($_LANG['affiliate_intro'][$affiliate['config']['separate_by']], $affiliate['config']['expire'], $_LANG['expire_unit'][$affiliate['config']['expire_unit']], $affiliate['config']['level_register_all'], $affiliate['config']['level_register_up'], $affiliate['config']['level_money_all'], $affiliate['config']['level_point_all']));
        }
        else
        {
            //推荐订单分成
            $sqlcount = "SELECT count(*) FROM " . $ecs->table('order_info') . " o".
                    " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id".
                    " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" .
                    " WHERE o.user_id > 0 AND (o.parent_id = '$user_id' AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)";


            $sql = "SELECT o.*, a.log_id,a.user_id as suid, a.user_name as auser, a.money, a.point, a.separate_type,u.parent_id as up FROM " . $ecs->table('order_info') . " o".
                    " LEFT JOIN".$ecs->table('users')." u ON o.user_id = u.user_id".
                    " LEFT JOIN " . $ecs->table('affiliate_log') . " a ON o.order_id = a.order_id" .
                    " WHERE o.user_id > 0 AND (o.parent_id = '$user_id' AND o.is_separate = 0 OR a.user_id = '$user_id' AND o.is_separate > 0)" .
                    " ORDER BY order_id DESC" ;

            /*
                SQL解释：

                订单、用户、分成记录关联
                一个订单可能有多个分成记录

                1、订单有效 o.user_id > 0
                2、满足以下之一：
                    a.订单下线的未分成订单 o.parent_id = '$user_id' AND o.is_separate = 0
                    b.全部已分成订单 a.user_id = '$user_id' AND o.is_separate > 0

            */

            $affiliate_intro = nl2br(sprintf($_LANG['affiliate_intro'][$affiliate['config']['separate_by']], $affiliate['config']['expire'], $_LANG['expire_unit'][$affiliate['config']['expire_unit']], $affiliate['config']['level_money_all'], $affiliate['config']['level_point_all']));

        }

        $count = $db->getOne($sqlcount);

        $max_page = ($count> 0) ? ceil($count / $size) : 1;
        if ($page > $max_page)
        {
            $page = $max_page;
        }

        $res = $db->SelectLimit($sql, $size, ($page - 1) * $size);
        $logdb = array();
        while ($rt = $GLOBALS['db']->fetchRow($res))
        {
            if(!empty($rt['suid']))
            {
                //在affiliate_log有记录
                if($rt['separate_type'] == -1 || $rt['separate_type'] == -2)
                {
                    //已被撤销
                    $rt['is_separate'] = 3;
                }
            }
            $rt['order_sn'] = substr($rt['order_sn'], 0, strlen($rt['order_sn']) - 5) . "***" . substr($rt['order_sn'], -2, 2);
            $logdb[] = $rt;
        }

        $url_format = "user.php?act=affiliate&page=";

        $pager = array(
                    'page'  => $page,
                    'size'  => $size,
                    'sort'  => '',
                    'order' => '',
                    'record_count' => $count,
                    'page_count'   => $max_page,
                    'page_first'   => $url_format. '1',
                    'page_prev'    => $page > 1 ? $url_format.($page - 1) : "javascript:;",
                    'page_next'    => $page < $max_page ? $url_format.($page + 1) : "javascript:;",
                    'page_last'    => $url_format. $max_page,
                    'array'        => array()
                );
        for ($i = 1; $i <= $max_page; $i++)
        {
            $pager['array'][$i] = $i;
        }

        $smarty->assign('url_format', $url_format);
        $smarty->assign('pager', $pager);


        $smarty->assign('affiliate_intro', $affiliate_intro);
        $smarty->assign('affiliate_type', $affiliate['config']['separate_by']);

        $smarty->assign('logdb', $logdb);
    }
    else
    {
        //单个商品推荐
        $smarty->assign('userid', $user_id);
        $smarty->assign('goodsid', $goodsid);

        $types = array(1,2,3,4,5);
        $smarty->assign('types', $types);

        $goods = get_goods_info($goodsid);
        $shopurl = $ecs->url();
        $goods['goods_img'] = (strpos($goods['goods_img'], 'http://') === false && strpos($goods['goods_img'], 'https://') === false) ? $shopurl . $goods['goods_img'] : $goods['goods_img'];
        $goods['goods_thumb'] = (strpos($goods['goods_thumb'], 'http://') === false && strpos($goods['goods_thumb'], 'https://') === false) ? $shopurl . $goods['goods_thumb'] : $goods['goods_thumb'];
        $goods['shop_price'] = price_format($goods['shop_price']);

        $smarty->assign('goods', $goods);
    }

    $smarty->assign('shopname', $_CFG['shop_name']);
    $smarty->assign('userid', $user_id);
    $smarty->assign('shopurl', $ecs->url());
    $smarty->assign('logosrc', 'themes/' . $_CFG['template'] . '/images/logo.gif');

    $smarty->display('user_clips.dwt');
}

//首页邮件订阅ajax操做和验证操作
elseif ($action =='email_list')
{
    $job = $_GET['job'];

    if($job == 'add' || $job == 'del')
    {
        if(isset($_SESSION['last_email_query']))
        {
            if(time() - $_SESSION['last_email_query'] <= 30)
            {
                die($_LANG['order_query_toofast']);
            }
        }
        $_SESSION['last_email_query'] = time();
    }

    $email = trim($_GET['email']);
    $email = htmlspecialchars($email);

    if (!is_email($email))
    {
        $info = sprintf($_LANG['email_invalid'], $email);
        die($info);
    }
    $ck = $db->getRow("SELECT * FROM " . $ecs->table('email_list') . " WHERE email = '$email'");
    if ($job == 'add')
    {
        if (empty($ck))
        {
            $hash = substr(md5(time()), 1, 10);
            $sql = "INSERT INTO " . $ecs->table('email_list') . " (email, stat, hash) VALUES ('$email', 0, '$hash')";
            $db->query($sql);
            $info = $_LANG['email_check'];
            $url = $ecs->url() . "user.php?act=email_list&job=add_check&hash=$hash&email=$email";
            send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1);
        }
        elseif ($ck['stat'] == 1)
        {
            $info = sprintf($_LANG['email_alreadyin_list'], $email);
        }
        else
        {
            $hash = substr(md5(time()),1 , 10);
            $sql = "UPDATE " . $ecs->table('email_list') . "SET hash = '$hash' WHERE email = '$email'";
            $db->query($sql);
            $info = $_LANG['email_re_check'];
            $url = $ecs->url() . "user.php?act=email_list&job=add_check&hash=$hash&email=$email";
            send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1);
        }
        die($info);
    }
    elseif ($job == 'del')
    {
        if (empty($ck))
        {
            $info = sprintf($_LANG['email_notin_list'], $email);
        }
        elseif ($ck['stat'] == 1)
        {
            $hash = substr(md5(time()),1,10);
            $sql = "UPDATE " . $ecs->table('email_list') . "SET hash = '$hash' WHERE email = '$email'";
            $db->query($sql);
            $info = $_LANG['email_check'];
            $url = $ecs->url() . "user.php?act=email_list&job=del_check&hash=$hash&email=$email";
            send_mail('', $email, $_LANG['check_mail'], sprintf($_LANG['check_mail_content'], $email, $_CFG['shop_name'], $url, $url, $_CFG['shop_name'], local_date('Y-m-d')), 1);
        }
        else
        {
            $info = $_LANG['email_not_alive'];
        }
        die($info);
    }
    elseif ($job == 'add_check')
    {
        if (empty($ck))
        {
            $info = sprintf($_LANG['email_notin_list'], $email);
        }
        elseif ($ck['stat'] == 1)
        {
            $info = $_LANG['email_checked'];
        }
        else
        {
            if ($_GET['hash'] == $ck['hash'])
            {
                $sql = "UPDATE " . $ecs->table('email_list') . "SET stat = 1 WHERE email = '$email'";
                $db->query($sql);
                $info = $_LANG['email_checked'];
            }
            else
            {
                $info = $_LANG['hash_wrong'];
            }
        }
        show_message($info, $_LANG['back_home_lnk'], 'index.php');
    }
    elseif ($job == 'del_check')
    {
        if (empty($ck))
        {
            $info = sprintf($_LANG['email_invalid'], $email);
        }
        elseif ($ck['stat'] == 1)
        {
            if ($_GET['hash'] == $ck['hash'])
            {
                $sql = "DELETE FROM " . $ecs->table('email_list') . "WHERE email = '$email'";
                $db->query($sql);
                $info = $_LANG['email_canceled'];
            }
            else
            {
                $info = $_LANG['hash_wrong'];
            }
        }
        else
        {
            $info = $_LANG['email_not_alive'];
        }
        show_message($info, $_LANG['back_home_lnk'], 'index.php');
    }
}

/* ajax 发送验证邮件 */
elseif ($action == 'send_hash_mail')
{
    include_once(ROOT_PATH .'mobile/includes/cls_json.php');
    include_once(ROOT_PATH .'mobile/includes/lib_passport.php');
    $json = new JSON();

    $result = array('error' => 0, 'message' => '', 'content' => '');

    if ($user_id == 0)
    {
        /* 用户没有登录 */
        $result['error']   = 1;
        $result['message'] = $_LANG['login_please'];
        die($json->encode($result));
    }

    if (send_regiter_hash($user_id))
    {
        $result['message'] = $_LANG['validate_mail_ok'];
        die($json->encode($result));
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = $GLOBALS['err']->last_message();
    }

    die($json->encode($result));
}
else if ($action == 'track_packages')
{
    include_once(ROOT_PATH . 'mobile/includes/lib_transaction.php');
    // include_once(ROOT_PATH .'mobile/includes/lib_order.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $orders = array();
    $sql = "SELECT order_id,order_sn,invoice_no,shipping_id,order_amount FROM " .$ecs->table('order_info').
            " WHERE user_id = '$user_id' AND shipping_status = '" . SS_SHIPPED . "'";
    $res = $db->query($sql);
    $record_count = 0;
    while ($item = $db->fetch_array($res))
    {
        $shipping   = get_shipping_object($item['shipping_id']);

        if (method_exists ($shipping, 'query'))
        {
            $query_link = $shipping->query($item['invoice_no']);
        }
        else
        {
            $query_link = $item['invoice_no'];
        }

        if ($query_link != $item['invoice_no'])
        {
            $item['query_link'] = $query_link;
            $orders[]  = $item;
            $record_count += 1;
        }
    }
    foreach ($orders as $key => $value) {
         $orders[$key]["son"]=order_goods($value["order_id"]);
    }
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page);
    $smarty->assign('pager',  $pager);
    $smarty->assign('orders', $orders);
    $smarty->display('user_transaction.dwt');
}
else if ($action == 'order_query')
{
    $_GET['order_sn'] = trim(substr($_GET['order_sn'], 1));
    $order_sn = empty($_GET['order_sn']) ? '' : addslashes($_GET['order_sn']);
    include_once(ROOT_PATH .'mobile/includes/cls_json.php');
    $json = new JSON();

    $result = array('error'=>0, 'message'=>'', 'content'=>'');

    if(isset($_SESSION['last_order_query']))
    {
        if(time() - $_SESSION['last_order_query'] <= 10)
        {
            $result['error'] = 1;
            $result['message'] = $_LANG['order_query_toofast'];
            die($json->encode($result));
        }
    }
    $_SESSION['last_order_query'] = time();

    if (empty($order_sn))
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['invalid_order_sn'];
        die($json->encode($result));
    }

    $sql = "SELECT order_id, order_status, shipping_status, pay_status, ".
           " shipping_time, shipping_id, invoice_no, user_id ".
           " FROM " . $ecs->table('order_info').
           " WHERE order_sn = '$order_sn' LIMIT 1";

    $row = $db->getRow($sql);
    if (empty($row))
    {
        $result['error'] = 1;
        $result['message'] = $_LANG['invalid_order_sn'];
        die($json->encode($result));
    }

    $order_query = array();
    $order_query['order_sn'] = $order_sn;
    $order_query['order_id'] = $row['order_id'];
    $order_query['order_status'] = $_LANG['os'][$row['order_status']] . ',' . $_LANG['ps'][$row['pay_status']] . ',' . $_LANG['ss'][$row['shipping_status']];

    if ($row['invoice_no'] && $row['shipping_id'] > 0)
    {
        $sql = "SELECT shipping_code FROM " . $ecs->table('shipping') . " WHERE shipping_id = '$row[shipping_id]'";
        $shipping_code = $db->getOne($sql);
        $plugin = ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php';
        if (file_exists($plugin))
        {
            include_once($plugin);
            $shipping = new $shipping_code;
            $order_query['invoice_no'] = $shipping->query((string)$row['invoice_no']);
        }
        else
        {
            $order_query['invoice_no'] = (string)$row['invoice_no'];
        }
    }

    $order_query['user_id'] = $row['user_id'];
    /* 如果是匿名用户显示发货时间 */
    if ($row['user_id'] == 0 && $row['shipping_time'] > 0)
    {
        $order_query['shipping_date'] = local_date($GLOBALS['_CFG']['date_format'], $row['shipping_time']);
    }
    $smarty->assign('order_query',    $order_query);
    $result['content'] = $smarty->fetch('library/order_query.lbi');
    die($json->encode($result));
}
elseif ($action == 'act_transform_points')
{
    $rule_index = empty($_POST['rule_index']) ? '' : trim($_POST['rule_index']);
    $num = empty($_POST['num']) ? 0 : intval($_POST['num']);


    if ($num <= 0 || $num != floor($num))
    {
        show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }

    $num = floor($num); //格式化为整数

    $bbs_key = substr($rule_index, 1);
    $rule_key = substr($rule_index, 0, 1);

    $max_num = 0;

    /* 取出用户数据 */
    $sql = "SELECT user_name, user_id, pay_points, rank_points FROM " . $ecs->table('users') . " WHERE user_id='$user_id'";
    $row = $db->getRow($sql);
    $bbs_points = $user->get_points($row['user_name']);
    $points_name = $user->get_points_name();

    $rule = array();
    if ($_CFG['points_rule'])
    {
        $rule = unserialize($_CFG['points_rule']);
    }
    list($from, $to) = explode(':', $rule[$rule_index]);

    $max_points = 0;
    switch ($rule_key)
    {
        case TO_P :
            $max_points = $bbs_points[$bbs_key];
            break;
        case TO_R :
            $max_points = $bbs_points[$bbs_key];
            break;
        case FROM_P :
            $max_points = $row['pay_points'];
            break;
        case FROM_R :
            $max_points = $row['rank_points'];
    }

    /* 检查积分是否超过最大值 */
    if ($max_points <=0 || $num > $max_points)
    {
        show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points' );
    }

    switch ($rule_key)
    {
        case TO_P :
            $result_points = floor($num * $to / $from);
            $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分
            log_account_change($row['user_id'], 0, 0, 0, $result_points, $_LANG['transform_points'], ACT_OTHER);
            show_message(sprintf($_LANG['to_pay_points'],  $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points');

        case TO_R :
            $result_points = floor($num * $to / $from);
            $user->set_points($row['user_name'], array($bbs_key=>0 - $num)); //调整论坛积分
            log_account_change($row['user_id'], 0, 0, $result_points, 0, $_LANG['transform_points'], ACT_OTHER);
            show_message(sprintf($_LANG['to_rank_points'], $num, $points_name[$bbs_key]['title'], $result_points), $_LANG['transform_points'], 'user.php?act=transform_points');

        case FROM_P :
            $result_points = floor($num * $to / $from);
            log_account_change($row['user_id'], 0, 0, 0, 0-$num, $_LANG['transform_points'], ACT_OTHER); //调整商城积分
            $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分
            show_message(sprintf($_LANG['from_pay_points'], $num, $result_points,  $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points');

        case FROM_R :
            $result_points = floor($num * $to / $from);
            log_account_change($row['user_id'], 0, 0, 0-$num, 0, $_LANG['transform_points'], ACT_OTHER); //调整商城积分
            $user->set_points($row['user_name'], array($bbs_key=>$result_points)); //调整论坛积分
            show_message(sprintf($_LANG['from_rank_points'], $num, $result_points, $points_name[$bbs_key]['title']), $_LANG['transform_points'], 'user.php?act=transform_points');
    }
}
elseif ($action == 'act_transform_ucenter_points')
{
    $rule = array();
    if ($_CFG['points_rule'])
    {
        $rule = unserialize($_CFG['points_rule']);
    }
    $shop_points = array(0 => 'rank_points', 1 => 'pay_points');
    $sql = "SELECT user_id, user_name, pay_points, rank_points FROM " . $ecs->table('users')  . " WHERE user_id='$user_id'";
    $row = $db->getRow($sql);
    $exchange_amount = intval($_POST['amount']);
    $fromcredits = intval($_POST['fromcredits']);
    $tocredits = trim($_POST['tocredits']);
    $cfg = unserialize($_CFG['integrate_config']);
    if (!empty($cfg))
    {
        $_LANG['exchange_points'][0] = empty($cfg['uc_lang']['credits'][0][0])? $_LANG['exchange_points'][0] : $cfg['uc_lang']['credits'][0][0];
        $_LANG['exchange_points'][1] = empty($cfg['uc_lang']['credits'][1][0])? $_LANG['exchange_points'][1] : $cfg['uc_lang']['credits'][1][0];
    }
    list($appiddesc, $creditdesc) = explode('|', $tocredits);
    $ratio = 0;

    if ($exchange_amount <= 0)
    {
        show_message($_LANG['invalid_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    if ($exchange_amount > $row[$shop_points[$fromcredits]])
    {
        show_message($_LANG['overflow_points'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    foreach ($rule as $credit)
    {
        if ($credit['appiddesc'] == $appiddesc && $credit['creditdesc'] == $creditdesc && $credit['creditsrc'] == $fromcredits)
        {
            $ratio = $credit['ratio'];
            break;
        }
    }
    if ($ratio == 0)
    {
        show_message($_LANG['exchange_deny'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    $netamount = floor($exchange_amount / $ratio);
    include_once(ROOT_PATH . './includes/lib_uc.php');
    $result = exchange_points($row['user_id'], $fromcredits, $creditdesc, $appiddesc, $netamount);
    if ($result === true)
    {
        $sql = "UPDATE " . $ecs->table('users') . " SET {$shop_points[$fromcredits]}={$shop_points[$fromcredits]}-'$exchange_amount' WHERE user_id='{$row['user_id']}'";
        $db->query($sql);
        $sql = "INSERT INTO " . $ecs->table('account_log') . "(user_id, {$shop_points[$fromcredits]}, change_time, change_desc, change_type)" . " VALUES ('{$row['user_id']}', '-$exchange_amount', '". gmtime() ."', '" . $cfg['uc_lang']['exchange'] . "', '98')";
        $db->query($sql);
        show_message(sprintf($_LANG['exchange_success'], $exchange_amount, $_LANG['exchange_points'][$fromcredits], $netamount, $credit['title']), $_LANG['transform_points'], 'user.php?act=transform_points');
    }
    else
    {
        show_message($_LANG['exchange_error_1'], $_LANG['transform_points'], 'user.php?act=transform_points');
    }
}
/*申请售后*/
elseif ($action == 'sale_service'){

    /* 订单商品 */
    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    $sql = "SELECT o.rec_id, o.goods_id,o.is_sale, o.goods_name, o.goods_sku, o.market_price, o.goods_number, g.goods_thumb, g.goods_img, " .
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, g.give_integral, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code, o.goods_attr_sku " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = o.goods_id " .
            " WHERE o.order_id = '$order_id' AND o.is_sale != 1 AND o.is_gift != 1";
    $goods_list = $db->getAll($sql);
    $smarty->assign('order_id', $order_id);
    foreach ($goods_list as $key => $value) {
        for ($i=1; $i <=  $value['goods_number']; $i++) { 
            $goods_list[$key]['goods_number_list'][]=$i;
        }
    }
    $smarty->assign('order_id', $order_id);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('sale_service.dwt');
}



/*售后表单*/
elseif($action =='sale_service_form' ){
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    $rec_id   = isset($_REQUEST['rec_id']) ? $_REQUEST['rec_id'] : 0;
    $goods_num = isset($_REQUEST['goods_num']) ? $_REQUEST['goods_num'] : 0;





    foreach ($rec_id as $key => $value) {
        $where = " rec_id = ".$value." OR ".$where;
    }
    $where =substr($where,0,-3); 
    $sql =  " SELECT o.rec_id,o.goods_name ,o.goods_attr,o.goods_price,o.goods_number,g.goods_thumb ".
            " FROM ".$ecs->table('order_goods')."AS o ".
            " LEFT JOIN ".$ecs->table('goods')." AS g ON g.goods_id =o.goods_id ".
            " WHERE o.is_sale != 1 AND o.is_gift != 1  AND".$where;
    $goods_list = $db->getAll($sql);
    foreach ($goods_list as $key => $value) {
        $goods_list[$key]['goods_number'] = $goods_num[$value['rec_id']];
        $price_count =$value['goods_price']*$goods_num[$value['rec_id']]+$price_count;
    }
    /* 获得用户订单收货地址 */
    $order_info = order_info($order_id);
    //赋值于模板
    $smarty->assign('shop_country',     $_CFG['shop_country']);
    $smarty->assign('shop_province',    get_regions(1, $_CFG['shop_country']));
    $smarty->assign('province_lists',    $province_list);
    $smarty->assign('city_lists',        $city_list);
    $smarty->assign('district_lists',    $district_list);
    $smarty->assign('p_list',    $p_list);
    $smarty->assign('c_list',    $c_list);
    $smarty->assign('d_list',    $d_list);
    $goods="";
    foreach ($goods_list as $key => $value) {
        $goods=$goods.$value['rec_id']."*".$value['goods_number'].",";
        $goods_number=$value['goods_number']+$goods_number;
    }
    $smarty->assign('goods_num', $goods);
    $smarty->assign('price_count', round($price_count,2));  
    $smarty->assign('order_info', $order_info);
    $smarty->assign('goods_number', $goods_number);
    $smarty->assign('goods_list', $goods_list);
    $smarty->display('sale_service.dwt');
}
/*生成售后单*/
elseif($action =='sale_service_handle' ){
        //接受表单数据
    $goods_list         = !empty($_REQUEST['goods_num'])?$_REQUEST['goods_num']:'';//申请售后的商品及数量
    $service_type       = !empty($_REQUEST['service_type'])?$_REQUEST['service_type']:'';//售后类型
    $question_note      = !empty($_REQUEST['question_note'])?$_REQUEST['question_note']:'';//问题描述
    $pic                = !empty($_REQUEST['pic'])?$_REQUEST['pic']:'';//图片资料
    $consignee          = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:'';//联系人名称
    $mobile             = !empty($_REQUEST['mobile'])?$_REQUEST['mobile']:'';//电话号码
    $payment_num        = !empty($_REQUEST['payment_num'])?$_REQUEST['payment_num']:'';//支付宝账号
    $add_time           = time();//申请时间
    $order_sn           = !empty($_REQUEST['order_sn'])?$_REQUEST['order_sn']:'';//订单号
    $user_id            = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';
    $handle_type        = !empty($_REQUEST['handle_type']) ? $_REQUEST['handle_type'] : 0;
    $refund_money       = !empty($_REQUEST['refund_money']) ? $_REQUEST['refund_money'] : 0;
    // dump($service_type);
    // dump($handle_type);
    // exit();
    //售后商品数据处理
    $goods=$goods_list;

    if (empty($goods)) {
        echo "请选择售后商品";
        exit();
    }



    /*判断是否重复提交*/
    //重组商品数据
    $where="";
    $goods_list = array_filter(explode(",",$goods_list));
    foreach ($goods_list as $key => $value) {
        $rec_id = substr($value,0,strpos($value,"*"));
        $goods_number = substr($value,(strpos($value,"*")+1));
    
        $where ="rec_id = ". $rec_id." OR ".$where;
    }
    $where =substr($where,0,-3); 

    $sql =  " SELECT rec_id FROM ".$ecs->table('order_goods').
            " WHERE is_sale = 1 AND (".$where.")";

    $is_sale=$db->getOne($sql);
    if(!empty($is_sale)){
        header("location: user.php?act=error");
        exit();
    }

    //图片处理
    if(!empty($pic)){
        foreach ($pic as $key => $value) {
            // 获取原图尺寸
            list($width, $height) = getimagesize($value);
            $url = "sale_pic/" . $order_sn . "/"; //文件路径
            $file_name = basename($value);//文件名称
            $new_url = $url . $file_name; //上传图片地址
            //检查上传目录是否存在
            if(!file_exists($url))
            {
                //创建目录
                mkdir($url);
            }

            //图片移动处理如果宽大于800进行压缩
            if($width>800){
                $new_width = 800;
                $new_height = round($height*(800/$width));
                $image_p = imagecreatetruecolor($new_width, $new_height);//建立新图片
                        // 获取图片格式
                $pinfo=pathinfo($value);  
                $ftype=$pinfo['extension']; 
                switch ($ftype) {
                    case 'jpg':
                        $image = imagecreatefromjpeg($value);//获取原来的图片
                        break;
                    case 'png':
                        $image = imagecreatefrompng($value);//获取原来的图片
                        break;
                    case 'gif':
                        $image = imagecreatefromgif($value);//获取原来的图片
                        break;
                    default:
                        # code...
                        break;
                }
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);//复制图片
            //将图片输出到文件夹
            switch ($ftype) {
                    case 'jpg':
                        imagejpeg($image_p, $value, 100);
                        break;
                    case 'png':
                        imagepng($image_p, $value, 100);
                        break;
                    case 'gif':
                        imagegif($image_p, $value, 100);
                        break;
                    default:
                        # code...
                        break;
                }
            //销毁图片
            imagedestroy($image_p);
            imagedestroy($image);
            }
            /* 加载ftp类并创建实例 */
            FTP()->upload($value, $new_url);
            $pic[$key] = $new_url;
        }
    }
    //标记商品为已申请售后
    $sql =  " UPDATE ".$ecs->table('order_goods').
            " SET is_sale = 1 ".
            " WHERE ".$where;
    $db->query($sql);

    //整理售后表信息
    $sale_info = array(
    'service_type'      => intval($service_type),
    'pic_1'             => $pic[0],
    'pic_2'             => $pic[1],
    'pic_3'             => $pic[2],
    'consignee'         => $consignee,
    'mobile'            => $mobile,
    'add_time'          => $add_time,
    'order_sn'          => $order_sn,
    'user_id'           => $user_id,
    'goods'             => $goods,
    'handle_type'       => $handle_type,
    'refund_money'      => $refund_money,
    'payment_num'       => $payment_num,
    );
        /* 把售后单信息写入sale_service表 */
    $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('sale_service'), $sale_info, 'INSERT', '', 'SILENT'); 
    $service_id=$db->insert_id();

    /*系统化语言*/
    $content = "买家于".date("Y-m-d h:i:s",time())."申请了售后<br/>";

    $content = $content."售后类型:".$_LANG['sale_question'][$service_type]."<br/>";
    $content = $content."处理方式:".$_LANG['handle_type'][$handle_type]."<br/>";
    $content = $content."退款金额为:".$refund_money."元<br/>";
    if(!empty($question_note)){
        $content = $content."问题描述:".$question_note."<br/>";
    }
    $handle_user = "(买家)".$_SESSION['user_name'];

    /*将操作记录*/
    $handle_record = array(
    'handle_user'       => $handle_user,
    'service_id'        => $service_id,
    'add_time'          => time(),
    'content'           => $content,
    'handle_id'         => 1,
    );
    $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
    header("location: user.php?act=done");
    exit();
}
/*完成售后单提示*/
elseif ($action == 'done'||$action == 'error')
{
    $smarty->display('sale_service.dwt');
}
//售后订单列表
elseif($action =='sale_list'){
    include_once(ROOT_PATH . 'includes/lib_transaction.php');
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $record_count = $db->getOne("SELECT COUNT(*) FROM " .$ecs->table('sale_service'). " WHERE  user_id = '$user_id'");
    $pager  = get_pager('user.php', array('act' => $action), $record_count, $page ,20000);

    $sale_list = get_user_sale($user_id, $pager['size'], $pager['start']);
    $smarty->assign('pager',  $pager);
    $smarty->assign('sale_list', $sale_list);
    $smarty->display('sale_service.dwt');
}
/*售后单详情*/
elseif ($action == 'sale_detail'){

    /* 售后详情 */
        $service_id = !empty($_REQUEST['service_id'])?$_REQUEST['service_id']:"";
            
        //获取售后表信息
        $sql= "SELECT * FROM ".$GLOBALS['ecs']->table('sale_service') ." WHERE service_id =".$service_id;
        $row = $GLOBALS['db']->getRow($sql);
        $goods_list = array_filter(explode(",",$row['goods']));
        //重组商品数据
        $where="";
        foreach ($goods_list as $key => $value) {
            $rec_id = substr($value,0,strpos($value,"*"));
            $goods_number = substr($value,(strpos($value,"*")+1));
            $goods[$rec_id]=$goods_number;
            $where =" rec_id = ". $rec_id." OR ".$where;
        }
         $where =substr($where,0,-3); 
         //获取商品信息
         $sql = " SELECT og.*,g.goods_thumb FROM ".$GLOBALS['ecs']->table('order_goods') ." AS og ".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods') ." AS g  ON g.goods_id = og.goods_id ".
                " WHERE ".$where;
         $order_goods = $GLOBALS['db']->getAll($sql);
         foreach ($order_goods as $key => $value) {
             foreach ($goods as $keys => $goods_number) {
                 if ($keys == $value['rec_id']) {
                     $order_goods[$key]['goods_number']=$goods_number;
                 }
             }
         }
         //获取操作记录
         $sql = " SELECT * FROM ".$GLOBALS['ecs']->table('handle_record') .
                " WHERE service_id =".$service_id.
                " ORDER BY add_time DESC";
         $handle_record = $GLOBALS['db']->getAll($sql);

         foreach ($handle_record as $key => $value) {
             $handle_record[$key]['add_time']=date("Y-m-d H:i:s",$value['add_time']);
         }
         //如果售后状态为待退货 查询退货单ID
         if($row['handle_state'] == 5){
            $sql = "SELECT return_id FROM ".$GLOBALS['ecs']->table('order_return_info')." WHERE service_id = $service_id";
            $return_id = $db->getOne($sql);
            $smarty->assign('return_id', $return_id);
                        //获取订单收货人信息
            $sql = "SELECT address,consignee,mobile FROM ".$GLOBALS['ecs']->table('order_info')." WHERE order_sn = ".$row['order_sn'];
            $consignee = $db->getRow($sql);
            $smarty->assign('consignee', $consignee);
         }
         //重组售后信息
         $row['goods']=$order_goods;
         $row['handle_record']=$handle_record;
         $sale_info = $row;
        
        $smarty->assign('express_list', $_LANG['ex']);
        $smarty->assign('sale_info', $sale_info);
        $smarty->display('sale_service.dwt');
}
/*AJAX提交退货单*/
elseif ($action == 'order_return'){
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    $return_info = !empty($_REQUEST['return_info'])?$_REQUEST['return_info']:'';
    $express_sn = $return_info['express_sn'];//快递单号
    $express_id = $return_info['express_id'];//快递ID
    $address    = $return_info['address'];//退货地址
    $mobile     = $return_info['mobile'];//退货地址
    $consignee  = $return_info['consignee'];//退货地址

    $return_id  = $return_info['return_id'];//退货单ID
    $service_id = $return_info['service_id'];//售后单ID



    $return['error']="1";
    $return['content']="";

    //查询售后状态是否为待退货 不是的话返回错误信息
    $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('sale_service')." WHERE service_id = $service_id";
    $sale_info = $db->getRow($sql);
    if($sale_info['handle_state'] != 5){
        $return['error']="2";
        $return['content']="请勿重复提交";
        die($json->encode($return));
    }
    //修改退货单信息
    $sql =  " UPDATE ".$GLOBALS['ecs']->table('order_return_info').
            " SET express_sn='$express_sn' , express_id ='$express_id' , address = '$address' ,consignee = '$consignee' ,mobile = '$mobile'".
            " WHERE return_id = $return_id ";
    $db->query($sql);

    // 通过处理方式判断后续处理

    switch ($sale_info['handle_type']) {
        case '2':
        //退货退款
    $refund_reason = $_LANG['refund_reason'][$sale_info['service_type']];//退款理由
    //自动生成退款单
    $refund_info = array(
    'order_sn'          => $sale_info['order_sn'],
    'refund_reason'     => $refund_reason,
    'refund_money'      => $sale_info['refund_money'],
    'add_time'          => time(),
    'handle_user'       => $sale_info['consignee'],
    'service_id'        => $sale_info['service_id'],
    'payment_num'       => $sale_info['payment_num'],
    );
    $db->autoExecute($ecs->table('refund'), $refund_info, 'INSERT', '', 'SILENT'); 
    //修改售后单状态
    $sql =  " UPDATE ".$ecs->table('sale_service').
            " SET handle_state = 6 ".
            " WHERE service_id = $service_id ";
    $db->query($sql);
    //记录操作     
    $handle_user = "(买家)".$_SESSION['user_nmae'];
    $content     = "【标题】 买家已退货 <br/>";
    $content     =  $content."【内容】  <br/>";
    $content     =  $content."物流公司： ".$_LANG['ex'][$express_id]." <br/>";
    $content     =  $content."退货单号：  ".$express_sn."<br/>";
    $content     =  $content."退货地址： ".$address." <br/>";
    $content     =  $content."收货人： ".$consignee." <br/>";
    $content     =  $content."收货人电话： ".$mobile." <br/>";

    $handle_record = array(
    'handle_user'       => $handle_user,
    'service_id'        => $service_id,
    'add_time'          => time(),
    'content'           => $content,
    'handle_id'         => 1,
    );
    $db->autoExecute($ecs->table('handle_record'), $handle_record, 'INSERT', '', 'SILENT'); 
    $return['error']="1";
    $return['content']="提交成功";
    die($json->encode($return));
            break;
        case '3':
        //退货补发
            # code...
            break;
        default:
            # code...
            break;
    }
}
elseif ($action == 'payCode'){
    include_once(ROOT_PATH .'includes/cls_json.php');
    $json = new JSON();
    $return['error']="0";
    $return['message']="";
    $return['content']="";
    $orderId = !empty($_POST['orderId'])?$_POST['orderId']:'';
    $order = order_info($orderId);
    //支付方式信息
    $payment_info = array();
    $payment_info = payment_info($order['pay_id']);
    //取得支付信息，生成支付代码
    $payment = unserialize_config($payment_info['pay_config']);
    /* 调用相应的支付方式文件 */
    include_once(ROOT_PATH . 'mobile/includes/modules/payment/' . $payment_info['pay_code'] . '.php');
    //获取需要支付的log_id
    $order['log_id']    = get_paylog_id($order['order_id'], $pay_type = PAY_ORDER);
    $order['user_name'] = $_SESSION['user_name'];
    $order['pay_desc']  = $payment_info['pay_desc'];
    /* 取得在线支付方式的支付按钮 */
    $pay_obj    = new $payment_info['pay_code'];
    $row['pay_online'] = $pay_obj->get_code($order, $payment,2);
    $return['content']=$row['pay_online'];
    die($json->encode($return));
}



/* 清除商品浏览历史 */
elseif ($action == 'clear_history')
{
    setcookie('ECS[history]',   '', 1);
}

/* 我的优惠券 */
elseif ($action == 'coupon'){
    /*获取优惠卷信息*/
    $user_id = $_SESSION['user_id'] ? $_SESSION['user_id'] : 0;
    $time = time();
    $sql =  " SELECT c.* , ct.* FROM ".$GLOBALS['ecs']->table('coupon')."AS c".
            " LEFT JOIN ".$GLOBALS['ecs']->table('coupon_type')."AS ct ON c.type_id = ct.type_id ".
            " WHERE c.user_id = '$user_id' ".
            " ORDER BY ct.type_name ASC";
    $coupon = $GLOBALS['db']->getAll($sql);
   /*重组数据*/
    foreach ($coupon as $key => $value) {
        /*过期优惠卷*/
        if ($value['end_time']<time()&&$value['is_use']=='0') {
            $couponOld[$key]=$value;
            $couponOld[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
            $couponOld[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
        }
        /*已使用优惠卷*/
        if ($value['is_use']=='1') {
            $couponUse[$key]=$value;
            $couponUse[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
            $couponUse[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
        }
        /*未使用优惠卷*/
        if ($value['is_use']=='0'&&$value['end_time']>time()&&$value['start_time']<time()) {
            $couponIsUse[$key]=$value;
            $couponIsUse[$key]['start_time_format'] = date('Y-m-d',$coupon[$key]['start_time']);
            $couponIsUse[$key]['end_time_format']   = date('Y-m-d',$coupon[$key]['end_time']);
            $couponIsUse[$key]['is_due']            = ($coupon[$key]['end_time']-$time)<172800?1:0;
        }
    }

    if (!empty($couponOld)) {
        $smarty->assign('couponOldCount', count($couponOld));
        $smarty->assign('couponOld', $couponOld);
    }
    if (!empty($couponUse)) {
        $smarty->assign('couponUseCount', count($couponUse));
        $smarty->assign('couponUse', $couponUse);
    }
    if (!empty($couponIsUse)) {
        $smarty->assign('couponIsUseCount', count($couponIsUse));
        $smarty->assign('couponIsUse', $couponIsUse);
    }

    $smarty->assign('top_title','我的优惠券');
    $smarty->display('user_coupon.dwt');
}
/* 处理 ajax 的注册请求 */
elseif ($action == 'ajax_register')
{
    include_once('includes/cls_json.php');
    $json = new JSON;
        include_once(ROOT_PATH . 'includes/lib_passport.php');
        $username = isset($_POST['username']) ? intval($_POST['username']) : '';
        $password = isset($_POST['password']) ? trim($_POST['password']) : '';
        $captcha = isset($_POST['captcha']) ? intval($_POST['captcha']) : '';
        $recommend_mobile = isset($_POST['recommend_mobile']) ? intval($_POST['recommend_mobile']) : '';
        $return   = array('error' => 0, 'content' => '','message'=>'');

        if (!empty($_POST['recommend_mobile'])) {
            /*查询用户是否存在*/
            $mobile_phone = $_POST['recommend_mobile'];
            $sql = 'SELECT user_id FROM '.$GLOBALS['ecs']->table('users')."WHERE mobile_phone = '".$mobile_phone."' AND agent_rank = '1'";
            $parentUid = $GLOBALS['db']->getOne($sql);
        }

        //判断用户名是否正确
        if(empty($username)){
            $return['error']   = 1;
            $return['message'] = '请输入手机号';
        }else if((!preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/",$username))&&(!preg_match("/^1[3|4|5|8][0-9]\d{8}$/",$username))){
            $return['error']   = 1;
            $return['message'] = '请输入正确的手机号';
        }

        //判断密码是否符合要求
        if (strlen($password) == 0){
            $return['error']   = 1;
            $return['message'] = '登录密码不能为空';
        }else if (strlen($password) < 6){
            $return['error']   = 1;
            $return['message'] = '登录密码不能少于 6 个字符';
        }

        if (strpos($password, ' ') > 0){
            $return['error']   = 1;
            $return['message'] = '密码中不能包含空格';
        }
        /*判断验证码是否正确*/
        if ($captcha!=$_SESSION['mobileCaptcha']) {
            $return['error']   = 1;
            $return['message'] = '验证码错误';
        }
        if (register($username, $password) !== false)
        {
            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'mobiel'."\t".
                get_user_browser()."\t".
                "注册");
            writelog('cplogs', $errorlog);

            $agent2_time = $parentUid?time():0;
            $agent_rank  = $parentUid?2:100;
            
            /*标记为已绑定手机号*/
            $sql = "UPDATE ". $GLOBALS['ecs']->table('users') . " SET is_mobile_validated = '1',parent_uid = '$parentUid', agent2_time = '$agent2_time' ,agent_rank = '$agent_rank' WHERE user_id = " . $_SESSION['user_id'];
            $GLOBALS['db']->query($sql);
            $return['error'] = 0;
            $return['message'] = "注册成功";
        }
        else
        {
            require_once(ROOT_PATH.'/plugins/ip/ip.php');
            $ip = new ip();
            $addr = $ip->ip2addr(real_ip());
            $errorlog = (
                time()."\t".
                $username."\t".
                '0'."\t".
                real_ip()."\t".
                $addr['country']."\t".
                'PC'."\t".
                get_user_browser()."\t".
                "注册失败");
            writelog('cplogs', $errorlog);

            $return['error']   = 1;
            $return['message'] = "注册失败，请重新输入！";
        }

    die($json->encode($return));
}elseif($action == "my_recommend"){

    //去拿用户信息
    $user_array = array();
    $sql = 'SELECT * FROM ' . $ecs->table('users') . ' WHERE user_id = '.$_SESSION['user_id'];
    $user_array = $db->getAll($sql);
    
    $one_user = array();
    
    if(!empty($user_array[0]['user_id'])){
        $user_array = $user_array[0];
        
        if($user_array['agent_rank']==2){
            //一级分销商判断
            $one_user = array();
            $sql = "select user_id,mobile_phone from ".$ecs->table('users'). " where user_id = ".$user_array['parent_uid']." and agent_rank = 1  ";
            $one_user = $db->getAll($sql);
            if(!empty($one_user[0]['user_id'])){
                $one_user = $one_user[0];
            }
        }
        
    }else{
        show_message("用户不存在");
    }
    
     $smarty->assign('one_user',$one_user);
     $smarty->assign('user',$user_array);
     $smarty->assign('top_title',"我的推荐人");
    $smarty->display('my_recommend.dwt');
}elseif($action == "my_recommend_action"){
    
    //一级分销商判断
    $binding_mobile = $_POST['recommend_mobile'];
    $one_user = array();
    $sql = "select user_id from ".$ecs->table('users'). " where mobile_phone = '".$binding_mobile."' and agent_rank = 1  ";
    $one_user = $db->getAll($sql);

    if(empty($one_user[0]['user_id'])){
        show_message("对方不是代理商用户");
    }
    $one_user = $one_user[0];
   //去拿用户信息
   $user_array = array();
   $sql = 'SELECT * FROM ' . $ecs->table('users') . ' WHERE user_id = '.$_SESSION['user_id'];
   $user_array = $db->getAll($sql);

   if(!empty($user_array[0]['user_id'])){
       $user_array = $user_array[0];

       if($user_array['agent_rank']!=100){
           show_message("只有普通用户才能使用此功能");
       }
       
       if($one_user['user_id']==$_SESSION['user_id']){
           show_message("不能绑定自己");
       }
       
       $sql="UPDATE ".$ecs->table('users'). "SET `agent2_time`=".time().",`agent_rank` = 2,`parent_uid` = ".$one_user['user_id']." WHERE user_id= '".$user_array['user_id']."'";
       $db->query($sql);
      
       show_message("已成功绑定");
   }else{
       show_message("用户不存在");
   }
   
}elseif($action == "my_distributor"){

    //去拿用户信息
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    //那到他的下一级用户列表
    $user_list = array();
    $sql = 'SELECT users.user_id,users.user_name,users.agent2_time,users.mobile_phone,orders.all_price 
            FROM ' . $ecs->table('users') . ' as users 
            left join (select order1.user_id,SUM(order1.goods_amount) as all_price from '.$ecs->table('order_info').' as order1
                        left join ' . $ecs->table('users') . ' as users1 on users1.user_id = order1.user_id 
                        where order1.add_time >= users1.agent2_time and order1.order_status=5 and order1.shipping_status=2 and order1.pay_status = 2
                        group by order1.user_id) as orders on orders.user_id = users.user_id
            WHERE parent_uid = '.$user_array['user_id'] ." and agent_rank = 2";
    $user_list = $db->getAll($sql);
    //处理数据
    foreach ($user_list as $key => $val){
        if(empty($val['all_price'])){
            $user_list[$key]['all_price'] = 0;
        }
        $user_list[$key]['agent2_time'] = date("Y-m-d H:i:s",$user_list[$key]['agent2_time']);
    }

    $smarty->assign("user_list",$user_list);
    $smarty->assign('top_title',"我的分销商");
    
    $smarty->display('my_distributor.dwt');
    
}elseif ($action == "distributor_detailed"){
    
    //去拿用户信息
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    
    $where = " AND orders.order_status = 5 AND orders.shipping_status = 2  AND orders.pay_status = 2 AND orders.add_time >= users.agent2_time ";
    if(!empty($_POST['time_select'])){
        if($_POST['time_select']==1){ //本月
            $time = strtotime(date("Y-m-01 H:i:s",time()));
            $where .= " and orders.add_time >= ".$time;
        }elseif ($_POST['time_select']==2){ //上个月
            $starttime = strtotime("-1 month",strtotime(date("Y-m-01 H:i:s",time())));
            $endtime = strtotime(date("Y-m-01 H:i:s",time()));
            $where .= " and orders.add_time >= ".$starttime." and orders.add_time < ".$endtime;
        }
        $smarty->assign("time_select",$_POST['time_select']);
    }
    
    //订单列表
    $order_list = array();
    $sql = 'SELECT orders.order_sn,orders.withdraw_status,users.user_id,users.user_name,users.mobile_phone,orders.goods_amount,orders.add_time
            FROM ' . $ecs->table('order_info') . ' as orders
            left join ' . $ecs->table('users') . ' as users on users.user_id = orders.user_id
            WHERE users.parent_uid = '.$user_array['user_id'] ." and users.agent_rank = 2 ".$where."
            order by orders.order_id DESC";
    $order_list = $db->getAll($sql);
    
    $withdraw_status_array = array("0"=>"未申请","1"=>"申请中","2"=>"已提现");
    
    //处理数据
    foreach ($order_list as $key => $val){
        $order_list[$key]['add_time'] = date("Y-m-d H:i:s",$order_list[$key]['add_time']);
        $order_list[$key]['withdraw_status'] = $withdraw_status_array[$val['withdraw_status']];
        //提成计算
        $order_list[$key]['commission_price'] = round($val['goods_amount']*COMMISSIONS_RATIO,2);
        
    }

    $smarty->assign("order_list",$order_list);
    $smarty->assign('top_title',"分销明细");
    
    $smarty->display('distributor_detailed.dwt');
    
}elseif ($action == "user_withdraw"){
    //提现逻辑
    $user_array = array();
    $user_array = get_user_all_info();
    
    if(empty($user_array['user_id'])){
        show_message("用户不存在");
    }
    //提现信息
    $order_list = array();
    $sql = 'SELECT orders.order_id
            FROM ' . $ecs->table('order_info') . ' as orders
            left join ' . $ecs->table('users') . ' as users on users.user_id = orders.user_id
            WHERE users.parent_uid = '.$user_array['user_id'] ." and users.agent_rank = 2 and orders.withdraw_status=0 and orders.order_status=5 and orders.shipping_status=2 and orders.pay_status=2 and orders.add_time >= users.agent2_time ";
    $order_list = $db->getAll($sql);
    
    if(count($order_list)<=0){
        show_message("暂时没有可提现的订单");
    }
    
    foreach ($order_list as $key => $val){
        //将订单的提现状态修改为已申请
        $sql = "UPDATE ". $ecs->table('order_info') . " SET withdraw_status = 1,commissions_ratio = ".COMMISSIONS_RATIO." WHERE order_id = ".$val['order_id'];
        $db->query($sql);
        
        $sql = "INSERT INTO " .$ecs->table('withdraw_log'). " (order_id, user_id, status,remark,inputtime)" .
            "VALUES ('$val[order_id]','$_SESSION[user_id]',1, '用户在前台操作，申请提现', ".time().")";
        $db->query($sql);
        
    }
    show_message("已成功申请提现");
}

?>